Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Learn Python the Easy Way

Learn python programming in 12 lessons


Learning to write code is easy and anyone with access to a computer can do it and it will probably force your brain to approach problem solving from a different angle. Python is one of the many programming languages you can learn and it's so simple yet powerful and was at one point the backend code used by YoutTube and currently used by Instagram.

This is an introduction to Python programming to help you get started before moving onto other sources and complex constructs. Use this as a glossary to help you keep track of where you need to go.

Lessons

 

Miscellaneous

 

read more

Cloning and Comparing Matrices Using Python

Learn python programming in 12 lessons


The last post showed you how to create and print nxn matrices. This one would show you how to create a copy a matrix and how to compare two matrix to check if they are equal. The first thing you need to understand about checking if two matrices are equal is that you need to check each and every element at each index in both matrix to see if they match. Take this example of a shell interaction

a = [[1,2,3],[4,5,6],[7,8,9]]
a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = a.copy()
b
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a == b
True
#make changes to one element in a
a[2][2] = 0
a
[[1, 2, 3], [4, 5, 6], [7, 8, 0]]
b
[[1, 2, 3], [4, 5, 6], [7, 8, 0]]
a == b
True
#was expecting the comparison to yield False

 There seem to be an error because a change was made in matrix a but it seems like this change cascaded to matrix b. Since changes were made to a, we expect it to be [[1, 2, 3], [4, 5, 6], [7, 8, 0]] and matrix b remain [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. When the comparison is made, we expect the answer to be False. But because the copy operator only pointed the variable b to the same memory location of matrix a, changes made to matrix a are also reflected in matrix b. This is definitely not what we want. To ensure that this mix up does not happen, we write out own copy and compare functions to our exact specification.

The clone matrix would like like this


def cloneMatrix(matrix):
    """return a copy of the matrix"""
    # create a dummy clone of the same size
    clone = createMatrix( len(matrix) ) #initialize dummy clone with zeros
    for i in range(len(matrix)):
        for j in range(len(matrix)):
            clone[i][j] = matrix[i][j] # replace all zeros in the clone matrix
    return clone

The output looks like this


cloneMatrix([[1,2],[3,4]])
[[1, 2], [3, 4]]
cloneMatrix([[1,2,3],[4,5,6],[7,8,9]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The function to compare the matrices would take two matrix as parameters and it looks like this

def matrixEqual(matrixA, matrixB):
    """check if the two 2d matrix are equal - return boolean value"""
    one, two = matrixA, matrixB
  
    # check if the two are the same size
    if len(one) != len(two):
        return False
    else:
        for i in range( len(one) ):
            for j in range( len(two) ):
                if one[i][j] != two[i][j]:
                    return False #break out of loop if a mismatch found
                else:
                    continue # continue checking if the items match
    return True

The output looks like this if run from the Python shell

# compare 2x2 matrix
matrixEqual([[1,1],[1,1]],[[1,1],[1,1]])
True
matrixEqual([[1,1],[1,1]],[[1,1],[1,0]])
False
matrixEqual([
[1,1],
[1,1]],
[
[1,1],
[1,0]])
False
# compare 3x3 matrix
matrixEqual( [[1,2,3], [4,5,6], [7,8,9]], [ [1,2,3], [4,5,6], [7,8,9]] )
True
matrixEqual( [[1,2,3], [4,5,6], [7,0,9]], [ [1,2,3], [4,5,6], [7,8,9]] )
False
read more

Creating and Printing 2 Dimensional Arrays Using Python

Learn python programming in 12 lessons


A matrix in Python is represented as a 2 dimensional array.

Creating a matrix is done by creating a single list of lists. In other words, a matrix in Python is an array that contains other arrays. Here are examples of matrices of different sizes:
2x2 -- [[0,0], [0,0]]
3x3 -- [[0,0,0], [0,0,0], [0,0,0]]
4x4 -- [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]

The steps you need to take when creating an nxn matrix are as follow
create a single empty list
repeat the steps below n times
           create another list with a single element
           multiply that list by n
           add that list to the outer list

Below is the Python code to create an nxn matrix


def createMatrix(n):
    """creates a matrix of size nxn"""
   
    matrix = [] # the outer matrix
   
    for i in range (n):
        matrix.append ([0] * n) #creates a 2-d list of size nxn
   
    return matrix

If the function above is executed, the output would look like this

createMatrix(1)
[[0]]
createMatrix(2)
[[0, 0], [0, 0]]
createMatrix(3)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
createMatrix(4)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
createMatrix(5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]


When it comes to printing the matrix, you would prefer to see rows and columns on the screen. This is achieved by printing each element in the list separately one list under the other. The Python code below does just that.


def printMatrix(matrix):
    """print out a nxn matrix"""
   
    for i in range( len(matrix) ): # for the rows
        for j in range( len(matrix) ): #for the columns
            print( matrix[i][j], end=' ' ) # prints one row
        print() # move to the next level

The output of the following function is as follow


printMatrix(createMatrix(2))
0 0
0 0
printMatrix(createMatrix(3))
0 0 0
0 0 0
0 0 0
printMatrix(createMatrix(4))
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
printMatrix(createMatrix(5))
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Below is the full code including the main method


 def createMatrix(n):
    """creates a matrix of size nxn"""
   
    matrix = [] # the outer matrix
   
    for i in range (n):
        matrix.append ([0] * n) #creates a 2-d list of size nxn
   
    return matrix


def printMatrix(matrix):
    """print out a nxn matrix"""
   
    for i in range( len(matrix) ): # for the rows
        for j in range( len(matrix) ): #for the columns
            print( matrix[i][j], end=' ' ) # prints one row
        print() # move to the next level
       
def main():
    print("\n\n2x2 matrix\n")
    printMatrix(createMatrix(2))
    print("\n\n3x3 matrix\n")
    printMatrix(createMatrix(3))
    print("\n\n4x4 matrix\n")
    printMatrix(createMatrix(4))
    print("\n\n5x5 matrix\n")
    printMatrix(createMatrix(5))


if __name__ == "__main__":
    main()
read more

Check If Its A Leap Year With Python

Learn python programming in 12 lessons


Most people know that that we have a leap year every fourth year but that is not exactly accurate. To understand the properties of a leap year, you would want to look up some facts on leap year on math is fun.

The main properties of a leap year are
  1. it is evenly divided by 4 meaning no remainder
  2. if condition 1 passes, then it should not be evenly divisible by 100
  3. it is evenly divisible by 400
In other words, a year is a leap year if it is evenly divisible by 4 or 400 and not evenly divisible by 100. That statement is going to makeup the the if statement in the Python program. Notice that the year 2000 is a leap year and so is 1600 and 2400 but not 1700, 1800, 1900, 2100, 2200, 2300. An extra condition is needed to compensate for this anomaly otherwise we might disregard the year 1600, 2000 and 2400 as not leap years.

The Python function can look something like this


# This function checks if the year is a leap year
def leapYear(year):
   
    # make sure the parameter is an integer
    year = int(year)
   
    # A year is a leap year if it is divisible by 400 or 4 and not by 100
    if (year%400 == 0 or year%4 ==0) and year%100 !=0:
        print(year,"is a leap year.")
    else:
        print(year,"is not a leap year.")
read more

Finding The Palindrome Using Python

Learn python programming in 12 lessons


A palindrome is defined as a phrase, number or string that reads the same way backwards. A number like 11, 1221, 2002 are all palindromes because they read the same when reversed. There are also strings that can read the same way in reverse such as lol, eye, madam, etc. Words, phrases or numbers that read the same when reversed are called palindromic.

In Python, the easiest way to find the palindrome of a string is to simply reverse the string and use logical operators to check if the two words are the same. For phrases, you might want to reverse the phrase and compare the phrases by ignoring the spaces and punctuation. For numbers, it is easier to convert it to a string and test it using the logical operator. Sometimes it helps to compare the word by ignoring the case and test either as all caps or small caps because "Eye" != "eye" in computing.

Another way of finding the palindrome of a number is to construct the number starting with the digits at the far end working all the way to the front. Notice that a number is a base 10 and to strip of the last digit, you continuously divide by 10 and retain the whole number whilst using the reminder to build a new number.

The following for loop is designed to do just that


# num is the parameter passed to the function
number = num
reversed = 0
for i in range(1,len(num)):   
        r = number % 10
        reversed = reversed * 10 + r * 10
        number = number // 10 #integer division

A simple function to test if a number or letter is a palindrome is as seen below


# This function checks if the word or number is a palindrome

def palindrome(word):
   
    # make sure the parameter is a string
    word = str(word)
   
    # reverse the word
    reversed = word[::-1]
   
    # compare the two words ignoring the case
    if word.lower() == reversed.lower():
        return True # or print ("Palindrome")
    else:
        return False # print("Not a palindrome")

The above code can also be written using a recursive algorithm that slices the character at index 0 and concatenating it with the rest of the string by placing it at the end when reversing the string. The part that reverses the code in the function above can be replaced with the line reversed = reverse(word) where reverse the recursive Python function for reversing a string.


# Recursive function for reversing a string
def reverse(string):
   
    if string == "":
        return string # Base case: empty string
    else: # Recursively reverse the string
        return reverse(string[1:]) + string[0]
read more

Finding Prime Numbers Using Python

Learn python programming in 12 lessons


A prime number is a number that is only evenly divisible by itself and 1 otherwise its regarded as a composite number. To test it a number is prime, you simple take a for loop with a range from 2 to to the number and inside the loop, you divide the number by all those numbers in the range. If you find a number that evenly divides the number, then you break because its obvious the number is not prime.
The for loop would look something like this

for i in range(2,num):          
            if num % i == 0:
                primes = False
                break
            else:
                primes = True

You can easily see that the above loop would take such a long time to execute if you are using a slow computer with little memory. The other trick that you can use to shorten the range of numbers up until the square root of the number. The full code to test if the number is prime using Python can look like this


# This function checks if the number is prime
def prime(num):
    primes = False
    num = int(num)   
         
    if num == 1:
        primes = False       
    elif num == 2:
        primes = True
    else:
        for i in range(2,num):           
            if num % i == 0:
                primes = False
                break
            else:
                primes = True
               
    return primes
read more

Lesson 12: Files and Exceptions in Python

Learn python programming in 12 lessons


You have probably already guessed that computer programs have the ability to write and read data to files. Files are identified by their unique filename which is why you don’t find the exact same filename in the same location.

There are two type of files that you will one across
Text files: strings terminated by a new line
Binary files: are not text files and store information as encoded by the application
Note that every text file is a binary file but every binary is not a text file.

Opening and closing files in Python

The syntax used to open a file is <file> = open (<filename>,<mode>)
To close the file, simply use <file>.close()
<file> represents a Python variable and <mode> can be either
  • r: to read only
  • w: to write
  • a: to append
There are 4 more other that you can read about here

f = open (“fileOne.txt”,”r")
The above syntax opens a file called fileOne.txt to read its contents. To read the content of the file, you can use either one of the following
f.read() —> reads the entire files in and stores it as one string
f.readline() —> reads only one line at a time
f.readlines() —> creates a list of strings with each list representing a line in the file

To write data to a file, the write function is used such as f.write(“End of file”) . This prints the line “End of file” to the file.

Reading and writing data to files is usually done by using exceptions in order to prevent the program from crashing when an error is encountered. It is generally good programming practice to use exceptions to catch errors especially when dealing with big programs. The Python syntax for exceptions is

try:
    statements
except <exception name>:
    statements
except <exception name>:
    statements
except <exception name>:
    statements
finally:
    statements

The main success scenario is contained in the try block. This means that every statements that we consider as the main code should be within this block because it will be the first to be executed.
If the try block does not successfully execute, the except block will be executed next sequentially starting with the first one that matches the error generate by the try block.
The finally block will always be executed and it is in this block where you close files.

One common error you will encounter when dealing with files is the IOError which is executed when the file cannot be located. Here is an example


try:
     f = open("theFile.txt", "r")
     data = f.read()
except IOError as one:
     print("\nfailed to open file")
     print(one,"\n")
finally:
     print("finally cleaning up")
    
Read more on excepts here

Here is a simply program to write the a right a bunch of triangles to theFile.txt
The pattern to write to the file are

*
**
***
****
*****
******
*******
********

********
********
********
********
********
********
********
********

********
*******
******
*****
****
***
**
*

The print sequence for the first right angle triangle is

def printT(n):
    for i in range (n):
        print( "*" * (i+1) )

The print sequence for the square is

def printT(n):
    for i in range (n):
        print( "*" * n )

The print sequence for the upside right angle triangle is


def printT(n):
    for i in range (n+1):
        print( "*" * (n-i) )

All that is left it to combine the three printing sequence into one function and enclose in the try block as we print to the file



def printT(n):
    filename = "theFile.txt"
   
    try:
        # Open the file
        f = open(filename, "w")
       
        f.write("output:\n")
       
        for i in range (n):
            f.write( "*" * (i+1) + "\n" )
       
        f.write( "\n" )
       
        for j in range (n):
            f.write( "*" * n + "\n" )
       
        f.write( "\n" )
       
        for k in range (n+1):  
            f.write( "*" * (n-k) + "\n" )
       
    except IOError as one:
        print("\nfailed to open file")
        print(one,"\n")
    finally:
        f.close()
        print("\n" + filename + " closed!")

printT(4)
# Output expected

# printT(4)
# *
# **
# ***
# ****

# ****
# ****
# ****
# ****

# ****
# ***
# **
# *
read more

Lesson 11: Recursion With Python

Learn python programming in 12 lessons


Recursion is simply defined as repeating some procedure until you can’t anymore. In computing, it is used to solve problems by breaking them into smaller parts by using a function that passes parameters to itself.
For each recursive function to work, 2 key elements are needed
a stopping condition (base case): This is the smallest simplest solution to the problem
at least one recursive call (recursive step): represent the problem reduced by some margin

Take note that any problem that can be solved using recursion can also be solved non-recursively. It is preferably to use a non-recursive solution to a problem if the problem size is very big because this can have a negative impact on the performance of the computer especially the memory.

To understand recursion, you need to understand the problem and estimate its size and impact on the performance of your computer. If your computer can handle the problem, determine if it can be solved recursively and establish its base case. If you know the base case, then the recursive step is simply a call to the function using a smaller parameter.

Think of a function to find the sum of the first n integers. If n is 5, then the sum is simply 0 + 1 + 2 + 3 + 4 + 5 = 15. A non recursive solution to the problem would require a loop similar to this

def sumOf(s):
   
    sum = 0
    for i in range(s+1):
        sum += i
    return sum

sumOf(5) = 15

If you are to use recursion, you would realise that the base case would have to be when you reach 0 which would indicate that we recursively call the function starting with the biggest parameter and reducing it until you reach 0. If n is 5, you start the recursive call with 5,4,3,2,1,0


def sumOf(s):
   
    # Base case
    if s == 0:
        return s
    # Recursive step
    else:
        return s + sumOf(s-1)

sumOf(5) = 15

Notice that Python only starts to add the numbers after the base cad has been executed. The whole time the recursive step is executed, the calls not executed are parked on a stack and they are removed one by one until it is empty.

Step 1: sumOf(5)
Step 2: 5 + sumOf(4)
Step 3: 4 + sumOf(3)
Step 4: 3 + sumOf(2)
Step 5: 2 + sumOf(1)
Step 6: 1 + sumOf(0)
Step 7: 0

After step 6, the base case is evaluated and 0 is returned.
Step 6 is then removed from the stack and evaluated as 1 + 0 which equals 1.
Step 5 is then removed from the stack and evaluates as 2 + 1 which equals 3.
Step 4 is then removed from the stack and evaluates as 3 + 3 which equals 6.
Step 3 is then removed from the stack and evaluates as 4 + 6 which equals 10.
Step 2 is then removed from the stack and evaluates as 5 + 10 which equals 15.
Since the stack is empty, the function stops executing and the final solution is 15.

If you were to find the length of a string, you would simply just use len(“String”) which would give the answer of 6. You could also do this recursively by slicing the string until it has a length of 0 with a recursive function that looks like this

def length(s):
   
    # Base case: empty string
    if s == '':
        return 0
    # Recursive step: slice of the first character
    else:
        return 1 + length(s[1:])

Python shell evaluation of the function

length('') = 0
length('star') = 4
length('python') = 6
length('yes') = 3
length('1') = 1

A recursive function to find the factorial(n) in Python would have a base case that gives a solution of 1 when n is 0 or when n is 1 because 0! = 1! = 1
The recursive function would look like this


def factorial(n):
   
    # Base case:
    if n == 0 or n == 1:
        return 1
    # Recursive step
    else:
        return n * factorial(n-1)

Evaluating the function in the Python shell produces

factorial(0) = 1
factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
factorial(5) = 120
read more

Lesson 10: Arrays and Dictionaries With Python

Learn python programming in 12 lessons


Arrays are ordered arrangement of values associated with one variable. Each value in an array is identified by its unique index value starting at 0 to n-1 where n is the number of items stored in the array (n also referred to as the size).
Arrays in Python are of variable length and mixed data types can be stored in one array. Arrays can also be defined as single or multi dimensional and in Python arrays are called list’s.

a = [] —> this is an empty array
a = [1,2,3] —> array of integer with size 3
a =  ['z','y','x’] —> array of string with size 3
a = [3, 2, 1, 'z', 'y', 'x', 1] —> mixed array of size 3

Just as it was done with strings, one can retrieve a particular item from an array by accessing its index using the same slicing techniques as done on strings. From the array a = [3, 2, 1, 'z', 'y', ‘x’] the following index gives
a[0] = 3
a[4] = ‘y'
a[2:4] = [1, 'z’]
a[0:6:2] = [3, 1, 'y’]
2 in a = True
’s’ in a = False
len(a) = 6


One can also process items in a list individually by using a for loop such as printing them as opposed to printing the whole list with print(a) which gives [3, 2, 1, 'z', 'y', ‘x].

for i in a:
    print(i)

output:
3
2
1
z
y
x

for i in a:
    print(i, end=' ')

output:
3 2 1 z y x

Just like with strings, arrays do come with built in functions. To see the list of all built in functions, type help() in the shell and press return and then type list and all list functions would be displayed.

Here are some common functions and how the behave if applied on the array a

append(object) —> appends (adds) object to the end of the list
a.append(’s’) gives a = [3, 2, 1, 'z', 'y', ‘x’, ’s']

insert(object,index) —> inserts an object before the index
a.insert(4,0) gives a = [4,3, 2, 1, 'z', 'y', ‘x’]

reverse —> reverses the order of the objects
a.reverse gives a = ['x', 'y', 'z', 1, 2, 3]


Arrays can also be defined to be multi dimensional and one of the most common used is the 2-d arrays which is very common in everyday applications such as the pictures and grid games. Multi dimensional arrays in Python are created by having multiple arrays in one array such as a = [[], [], []]

We might be interested in creating a grid with 3 rows and 3 columns, then our 2-d array would look like a = [[0,0,0],[0,0,0],[0,0,0]]. Elements in a multi dimensional array are accessed with the statement a[index][index] where by the first bracket refers to the array at the index and the second bracket refers to the element at the index of the array referenced by the first bracket.
Example a = [[1,2,3], [4,5,6], [7,8,9]]
a[0] only refers to the array at index 0 which is [1,2,3]
a[0][1] refers to the element at index 1 on the array at the index 0 of array a which is element 2
a[1][2] refers to 6
a [2][1] refers to 8


You should also be aware of another Python data structure that does not care for the order of the values stored in it. This data structure is called a dictionary and it maps a set of keys to some values. Dictionaries in Python are declared such as follow

Dic = {'g': 'girl', 'b': 'boy', 'p': 'position'}

The above dictionary Dic maps the keys g,b,p to the values girl,boy,position. The following computation can be done on a dictionary.

Check if a key is in the dictionary
'g' in Dic —> True
's' in Dic —> False

Access a particular key
Dic['g’] —> ‘girl'

Get an array of the keys
Dic.keys() —> ['g', 'b', 'p’]

Get a list of the values
Dic.values() —> ['girl', 'boy', 'position’]

To see the rest of built functions that can be used to do computation on a dictionary, type help(dict) in the python shell.
read more

Lesson 9: String Data Structure in Python

Learn python programming in 12 lessons


Strings in Python behave just the same way as strings in other programming languages. They are made up of any character enclosed in single, double or triple quotes. These are all regarded as string

'This is PYTHON!'
"This is PYTHON!"
"""This is PYTHON!"""
The last string in triple quotes is called a doc string and it can be accessed from the python shell using the expression print(function name.__doc__). So when you want to include information in your functions that can help programmers understand what the function does, you should put them in a triple quote.

Strings are indexed starting at 0 to the length of the string. The length of a string is given by the function len(string) and this function loos something like this


def length(s):
    """This function returns the length of a string"""
    l = 0
    for i in s:
        l += 1
    return l # equivalent to print(l)

Evaluating the function in the Python shell produces
>>>length('crazy') or length("crazy")
      5
>>>print(length.__doc__)
      This function returns the length of a string

0 1 2 3 4 <— index
c r  a z y <— characters

-5 -4 -3 -2 -1 <— index
c    r   a  z   y <—characters

The line for i in s in the function above is traversing the string starting at index 0 to the end of the string which corresponds to length(s)-1. Take note that when a string has length n, its index go from 0 to n-1. Take note that strings can also be accessed in reverse starting at the end and counting backwards. The index n-1 corresponds to index -1 and index 0 corresponds to -n where n is the length of the string.


Because strings are used a lot in Python, they have a well developed class that has so many useful built-in functions such as

S.capitalize() —> Return a capitalized version of S
S.isalpha() —> Return True if all characters in S are alphabetic
S.isdigit() —> Return True if all characters in S are digits
S.find() —> Return the lowest index in S where substring sub is found
S.lstrip() —> Return a copy of the string S with leading whitespace removed.
S.rstrip() —> Return a copy of the string S with trailing whitespace removed.
S.split() —> Return a list of the words in S

To see the rest of built in string functions, type help(str) in your Python shell. To view the doc string of a specific string function like count, use the expression print(str.count.__doc__).

The functions found in the string class str are not the only things that can be done on a string, you might want a function that reverses the order of the string or one that returns a section of the it called a substring. You will have to write your own functions because those functions are not built in.
To be able to get a substring of a function, you need to know of a very useful functionality called slicing. slicing involves using any of these three parameters s[start,end,skips]
start refers to the starting index
end refers to the ending index
skips refers to the number of indexes to be examined
Look at this slicing example that uses string s = “crazy"

s[0] —> 'c'
s[len(s)-1] —> 'y'
s[-1] —> 'y'
s[2] —> 'a'
s[-2] —> ‘z'
s[:] —> 'crazy'
s[0:1] —> 'c'
s[0:4] —> 'craz'
s[-3:-1] —> ‘az’
s[0:4:2] —> ‘ca’
s[0:5:2] —> ‘cay’

There are three ways of reversing a string in Python by slicing it
s[-1::-1] —> 'yzarc'
s[len(s)::-1] —> 'yzarc'
s[::-1] —> ‘yzarc'

The first and last method are preferred because they don’t require you to calculate the length, you simply just access the last index in reverse (-1).

Here is a function to reverse a Python string by slicing it


def reverse(s):
   
    return s[::-1]
read more

Lesson 8: Repetitions

Learn python programming in 12 lessons


You should remember from the previous posts that an algorithm has steps, decisions and receptions of steps. By repetitions, we mean loops and Python supports two loop structures
  • for loop
  • while loop
These structures are further enhanced by loop control statements such as break, continue and the pass.
Loops can also be used to alter the flow of the program by executing them when some conditions are met by using if statements. This pretty much means that there is no limits as to what you can do with loops, you can have multiple loops inside each other but this is not recommended especially when you are dealing with large input data.

A loops would have 2 main elements, namely the body which entails the steps to be repeated, the terminating condition which is tested on each iteration of the loop. You can also call the terminating condition as a guard condition because it guards the body from being executed if the control statement does not evaluate to true.

Say we wanted to alter our program AddThreeNums.py so that it finds the average of more than three numbers depending on how many numbers the user wants to enter and print the new average every time a new number is entered. We can use a for loop and the program would look like this


# Program to display the average of three numbers on the screen
# Take note that using eval() function is equivalent to using int()


def getNumber():
    return input("Enter a number: ")

def main():
    itr = int(input("How many numbers would you like to enter: "))
    total = 0
    average = 0
   
    for i in range (itr):
       
        num=getNumber()
        total += eval(num) # equivalent to total = total + eval(num)
        average = total/(1+i) # equivalent to average = average + total/(i+1)
        print("\nTotal:", total)
        print("Average:", average)

if __name__ == '__main__':
    main()

A for loop has the following structure

for var in sequence:
    body
var is the variable that keeps track of the loops iterations
sequence is range of numbers var can hold at each iteration.
body represents all steps that need to be repeated

The line for i in range (itr): can be represented in 5 different ways. Assume that itr = 10, then the following lines would mean

for i in range (itr) means i can take on values 0,1,2,3,4,5,6,7,8,9
for i in range (1,itr) means i can take on values 1,2,3,4,5,6,7,8,9
for i in range (0,itr,2) means i can take on values 0,2,4,6,8
for i in range (itr,1,-1) means i can take on values 10,9,8,7,6,5,4,3,2
for i in range (-itr,0) means i can take on values -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

The other loop structure is the while loop and this loop has the following structure

while condition
    body
condition is the guard statement that permits the steps outlined in the body to be repeated only if the condition evaluates to true. So you can see that the while and for loop are interchangeable. The for loop in the AddThreeNums.py program can also be replaced by the while loop to achieve the same result as shown here


# Program to display the average of three numbers on the screen
# Take note that using eval() function is equivalent to using int()


def getNumber():
    return input("Enter a number: ")

def main():
    itr = int(input("How many numbers would you like to enter: "))
    total = 0
    average = 0
   
    i = 0
    while (i != itr):
       
        num=getNumber()
        total += eval(num) # equivalent to total = total + eval(num)
        average = total/(1+i) # equivalent to average = average + total/(i+1)
        print("\nTotal:", total)
        print("Average:", average)
        i += 1  # equivalent to i = i + 1

if __name__ == '__main__':
       main()
read more

Lesson 7: Conditional Program Execution

Learn python programming in 12 lessons


Python programs are written to either be run as programs or modules that have methods that are used by other programs when imported. Sometimes a module can be used as both a module and a program and to ensure that the main method is not run when the program is imported into another program, a conditional statement is used.
Take for example the program DistributeGrade.py from the previous post. it has the allocateGrade method which can be very useful to other programs but you would definitely not want the part that asks the user to enter a grade to be imported and executed. Because of this, that part is put into a method we call main and the control statement is added at the end as seen below


#Name this file DistributeGrade.py

def allocateGrade(mark):
    if (mark < 0 or mark > 100):
        print("Invalid mark!")
    elif (mark > 79):
        print("A")
    elif (mark > 74 and mark <=79):
        print("B")
    elif (mark > 69 and mark <=74):
        print("C")
    elif (mark > 59 and mark <= 69):
        print("D")
    elif (mark > 49 and mark <= 59):
        print("E")
    else:
        print("F")

def main():
    marks = input("Enter a grade: ")
    allocateGrade(eval(marks))

if __name__ == '__main__':
    main()


In the program above, you see the last control statement with the __name__ and __main__ variable. Before you know why it is there, remove that whole line and try running your program and you will notice that it does not execute because that line is missing. But if you remove the last condition statement and get rid of the main method, the program would run.

By using the __name__ variable, you are actually saying that if this program is imported into another program, do not run the main method but just allow the use of the functions. So if the file containing the program above is imported into another program maybe because the person wants to use the allocateGrade method, then the __name__ variable will be replaced by the file name contacting the method.

This means if you import the file DistributeGrade.py into another Python program, __name__ variable would be replaced by DistributeGrade but if you press run within the DistributeGrade.py file, the __name__ variable would be replaced by the name of the main method. Note that the name of the main method does not necessarily have to be called main, it can be whatever you call it. But main is preferred because it is an industry standard.
read more

Lesson 6: Selection Statements and Flow Control

Learn python programming in 12 lessons


Remember that an algorithm has three main elements which are steps, decisions and repetitions. When we talk of selections, we are referring to statements that require some form of decision to be taken which can alter the program flow. Sometimes these statements need to be repeated over and over until some terminating condition is satisfied.

In Python, decisions are handled by decision structures and one of the most common is the if-else statement. Any example of an if-else statement that checks the persons age and determines if that person is a minor or adult can look like this


if (age < 18):
    print(“Minor”)
else:
    print(“Adult”)

Decision structures make use of relational operators such as seen in the table below
> less than
>= less than or equal to
< greater than
<= greater than or equal to
== equal to
!= not equal to

Note that the condition age<18 will either evaluate to true or false. This implies that conditions are boolean expressions and in Python, they are identified by the literal True and False (take note of the capital letter).

How would you go about arranging the control statements for a grade allocation program that prints the following output based on what marks is entered by the user?
A — 80 - 100
B — 75 - 79
C — 70 - 74
D — 60 - 69
E — 50 - 59
F — 0 - 49

The if statements can look something like this


if (mark > 79 and mark <=100):
    print("A")
if (mark > 74 and mark <=79):
    print("B")
if (mark > 69 and mark <=74):
    print("C")
if (mark > 59 and mark <= 69):
    print("D")
if (mark > 49 and mark <= 59):
    print("E")
if (mark > 0 and mark <=49):
    print("F")
else:
    print("invalid marks")

It is important that you notice that it is probably best to check if a valid grade is entered at the beginning of the if statements because this would save time and avoid checking the rest of the control statements.
Another improvement is to make use of the elif keyword which stands for else-if. With all these improvements, the program would look like this


#Name this file DistributeGrade.py

def allocateGrade(mark):
    if (mark < 0 or mark > 100):
        print("Invalid mark!")
    elif (mark > 79):
        print("A")
    elif (mark > 74 and mark <=79):
        print("B")
    elif (mark > 69 and mark <=74):
        print("C")
    elif (mark > 59 and mark <= 69):
        print("D")
    elif (mark > 49 and mark <= 59):
        print("E")
    else:
        print("F")

marks = input("Enter a grade: ")
allocateGrade(eval(marks))


Imagine you had to run the program above on a million records, it would definitely take a long time to execute. One trick you can you is to realise that not everyone is going to hit the top grade, so it would probably make sense to start the condition statements with F and working up to A.
read more

Lesson 5: Functions, Numbers and Libraries

Learn python programming in 12 lessons


Functions in any programming language are used to remove duplications which simplifies code and make it pleasant to read. For example in the AddThreeNums.py program from the previous post, you would have noticed that we kept asking the user to enter a number three times. We could replace those lines with a function instead that is invoked each time we want a new number.

Functions in Python are identified by a keyword def followed by the name of the function which should not be a reserved word. Code that belong to the function should be indented so that they lie inside def.
The function to ask a user for input can be defined as follow


def getNumber():
    return input(“Enter a number ”)

This function would then be placed at the top of the program before the part where we ask for the user to enter the number.
The new program would then look like this


def getNumber():
    return input("Enter a number: ")

num1 = getNumber()
num2 = getNumber()
num3 = getNumber()

total = eval(num1) + eval(num2) + eval(num3)
average = total/3

print("\nTotal:", total)
print("Average:", average)

You might have noticed that when creating variables in Python, you do not declare the type such as integer, float, string or list. Python seems to accept what ever literal you assign to the variable. One variable can go from holding an integer to holding a list or a string all without changing the variable type. This is because Python is a dynamically typed language which means that a variable is nothing more but a value bound to a name. To illustrate this phenomenon, take a look at this:

>>> x = "strer"

>>> type(x)

<class 'str'>

>>> x = 4

>>> type(x)

<class 'int'>

>>> x = 4.3

>>> type(x)

<class 'float'>

>>> x = {2,4,5}

>>> type(x)

<class 'set'>

>>> x = [1,2,3]

>>> type(x)

<class 'list'>

>>> x = (3,4,5)

>>> type(x)

<class 'tuple'>

>>> x = (1+3j)

>>>type(x)

<class ‘complex'



As you can see, the variable x is not restricted to any one type and this is because Python is a dynamically typed language.

The function type() is used to tell what type of data is stored in the variable.

There are two types of numeric data types that are accepted by Python. One is an integer (no decimal) and the other is a float (has decimal). Floats are only an approximation of the real number it represents and this is because floating point take up a large portion of the memory and they are usually truncated after the 16th decimal point.


>>> import math

>>> math.pi

3.141592653589793

Because of this, numeric data types are handled differently by some some arithmetic operators such as the division. There is one division (/) that gives a floating point answer and the other division (//) strictly gives an integer ignoring the decimal.


>>> 2/3

0.6666666666666666

>>> 2//3

0

>>> 12/5

2.4

>>> 12//5

2

>>> 14/3

4.666666666666667

>>> 14//3

4

Familiarize your self with Python's numeric operators

Take note that the exponent operator for python is ** and not ^


>>> 2^3

1

>>> 2**3

8

>>> 4^2

6

>>> 4**2

16

The ^ in Python represents XOR operator.

When evaluating mathematical expressions in Python, the type of the expression is considered and like for like produced like. An int with an int will produce an int, a float with a float produces a float. An int with a float will produce a float because it is easier to convert an int to a float and this preserves information. If floats are converted to ints in a mixed type expression, information would be lost and inaccurate results would be produced. For example, 1/4 + 2 would produce 2.25 and this is equivalent to 1/4 + 2.0.



There are many other functions that are available for use with Python but in some cases, you have to explicitly avail them by using the import keyword. One such library is the math library and this contains functions such as sin(x), cos(x), exp(x), factorial(x), etc.
Here is a list of all functions available in the math library
Other libraries available in Python are: All Python Modules
read more

Lesson 4: Input, Output and Assignments

Learn python programming in 12 lessons


A python program can also accept input from the user and this is used by the input() function. The python program AddThreeNums.py can be updated to accept input from a user and store them in the three variables as follow


num1 = input(“Enter the first number”)
num2 = input(“Enter the second number”)
num3 = input(“Enter the third number”)

total = eval(num1) + eval(num1) + eval(num4)
average = total/3

print(“Total”, total)
print(“Average”, average)

The eval function is used to convert a string that is a number into an integer.

The print function used to provide the output to the screen is an interesting function. In Python 3, you are able to change a number of things in the printing pattern of any expression. When printing(1,2,3,4,5), The print command automatically inserts a space between the numbers separated by the commas. Those spaces can be replaced by any character sequence of your choice such as print(1,2,3,4,5,sep=‘’) which would print 12345 with no spaces.

>>> print(1,2,3,4,5)

1 2 3 4 5

>>> print(1,2,3,4,5,sep='')

12345

>>> print(1,2,3,4,5,sep='=')

1=2=3=4=5

>>> print(1,2,3,4,5,sep='&')

1&2&3&4&5

>>> print(1,2,3,4,5,sep='*')

1*2*3*4*5

>>> print(1,2,3,4,5,sep='no')

1no2no3no4no5

>>> print(1,2,3,4,5,sep='!')

1!2!3!4!5

Also take note that the print function automatically prints a new line once it has run out of things to print. This newline brings the cursor to the next line to print a different sequence on a new line. To change the end character from a newline to any character of your choice, the end keyword is used. The end keyword can be used as follows


>>> print(1,2,3,4,5,end=’STOP')

1 2 3 4 5STOP>>>

>>> print(1,2,3,4,5,sep=‘no’,end=‘*')

1no2no3no4no5*>>>

>>> print(1,2,sep=‘no’,end=‘\n')

1no2

>>> print(1,sep=‘no’,end=‘*')

1*>>>

You should take note that the sep keyword is only invoked if there is another item in the printing queue. The end keyword is only invoked once the printing queue is empty.

There are a number of predefined characters that can be used with the print function such as a tab denoted by \t and a single quote denoted by \’. The use of a backslash is called escaping the character sequence and to print the backslash, you have to escape it as \\. The first backslash encountered in the printing sequence notifies the interpreter that the next character is not there by mistake but you actually wish to print it as it appear. Here are a list of other character sequence escaped in Python.
\t --> tab
\n --> new line
\b --> back space
\s --> space
\" --> quotation mark (")
\' --> apostrophe (')

You have already encountered assignments in Python in the program AddThreeNums.py program above and one such example is average=total/3. Python can also do multiple assignments on the same line like


w,x,y,z = 1,2,3,4

The above assignment is equivalent to


w = 1

x = 2

y = 3

z = 4

Python is also able to handle double swapping assignments in one line without the need to have a temporary variable to facilitate the process. Say you wanted the numbers in x and y above to be swapped, you could introduce a new variable and do the swap like this


temp = x

x = y

y = temp

The three lines above are equivalent to the single line  
x,y = y,x
read more

Lesson 3: A Python Program

Learn python programming in 12 lessons


Python programs are identified by the file extension “.py" for example HelloWorld.py would be the python file containing the Hello World program.

A python program would contain any of the elements below
  1. Variables: used to provide easily identifiable names to objects example of good names for variables are x, y, z, name, boy, girl, school, this_school, my_wallet, thisSchool, myWallet, etc
  2. Functions: used to perform evaluations on parameters e.g. sqrt(4)
  3. assignments statements: used to associates variables with objects e.g. x=6
  4. Input statements: used to request input from the user. This are easily identified by the input() function. e.g. input(“Please enter a number: “)
  5. Output statements: used to display items on the screen. This are given by the print() function. e.g print(“Hello world!”)
  6. Comments: used to provide clarity to future programmer reading your code. Any line of code preceded by # in python is regarded as a comment and would be ignored when the program is executed.
When naming your program, function or variable, you would want to not use a reserved python word such as def, del, is, in, import, while, etc. Look at the complete list of reserved word in Python and know them by heart. The following line of code does just that.

import keyword
keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Now that you are aware of some of the elements of a program, you should be ready to start writing your own python programs. The program below calculates the average of three numbers and displays it on the screen.
#Program to display the average of three numbers on the screen
#program name: AddThreeNums.py

num1 = 1
num2 = 2
num3 = 3


total = num1 + num2 + num3
average = total/3


print(total)
print(average)
This program would output
6
2

This would be considered as a bad program because it does not inform the user of the program as to what the 6 and 2 represents. It would be ideal to display total and average next to their corresponding values. The program below is an improvement to the first
#Program to display the average of three numbers on the screen

num1 = 1
num2 = 2
num3 = 3


total = num1 + num2 + num3
average = total/3


print(“Total”, total)
print(“Average”, average)
The correct output would be
Total: 6
Average: 2.0

If your program gives a different output other than the one above, then you are probably not using python 3. Note that average is a double number and to convert it to an integer, enclose it like int(average) to get the output below.
Total: 6
Average: 2
read more

Lesson 2: The Python Shell

Learn python programming in 12 lessons


One of the very reason’s Python is powerful is because it has that simple interactive shell that a user can use to evaluate expressions without necessarily writing a program.

Expressions typed in the shell that cannot be evaluated are simple echoed back. For example, if you type a string like “Hello word!”, the shell will echo back ‘Hello world!’. If you type a number such as 2, the shell will echo the same number back. If an arithmetic expression like 3+2 is typed in, the shell will rather evaluate it and display 5. Boolean expression can also be evaluated in the shell. If you type 5==2, the shell will evaluate this and display false because 5 and 2 are not equal.

Python shell can also do computation on strings such as concatenations. If you type “Spider”+”man”, the shell evaluates this to ‘Spiderman’. 2*”Spider”+”man” or “Spider”*2+”man” evaluates to ‘SpiderSpiderman’. 
The shell can also evaluate expressions that makes use of functions. “Hello world!” can be enclosed into the function that displays items to the screen such as print(“Hello world!”) which would display Hello world! instead of ‘Hello world!’.

There are other functions such as min and max to display the minimum and maximum. 
For example min(1,2,3,4) will evaluate to 1 and max(1,2,3,4) will evaluate to 4. to find the square root of 4, you would type sqrt(4) but this would give an error because the library containing the sort function is not directly available, you would have to tell Python that you want to make use of functions in the math library by importing it with the line import math. 
The correct way to reference the square root function in the math library is by using the expression math.sqrt(4) which would evaluate to 2.0 which is double number.

If you ever need to read up on a function, you simply type help() into the interactive shell and you will be provided with the command prompt help>. To exit this prompt, you just hit the return(enter) key and the prompt returns to >>>. 

For example

help> min
min(...)
    min(iterable[, key=func]) -> value
    min(a, b, c, ...[, key=func]) -> value
   
    With a single iterable argument, return its smallest item.
    With two or more arguments, return the smallest argument.

help> max
Help on built-in function max in module __builtin__:

max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value
   
    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

help> abs
Help on built-in function abs in module __builtin__:

abs(...)
    abs(number) -> number
   
    Return the absolute value of the argument.

The other method of getting more information on a function if you know it exist is to use access the function’s doc string using this line print(function.__doc__)

For example

>>>print(eval.__doc__)
      eval(source[, globals[, locals]]) -> value

      Evaluate the source in the context of globals and locals.
      The source may be a string representing a Python expression
      or a code object as returned by compile().
      The globals must be a dictionary and locals can be any mapping,
      defaulting to the current globals and locals.
      If only globals is given, locals defaults to it.

>>>print(abs.__doc__)
      abs(number) -> number

      Return the absolute value of the argument.

>>>print(max.__doc__)
      max(iterable[, key=func]) -> value
      max(a, b, c, ...[, key=func]) -> value

      With a single iterable argument, return its largest item.
      With two or more arguments, return the largest argument.

The python shell is very powerful and it should usually be your go to place when you are testing an expression or you simply want to find out more information on a function.
read more

Lesson 1: an Algorithm, Pseudocode and a Program

Learn python programming in 12 lessons


A computer program is nothing more than a set of instructions that's is used by the computer to performed a task by sequentially following the instructions as stated in the program. When you find yourself with a program that gives undesired results, then you should know that there must be something wrong with the instructions you prepared. To find the error also known as a bug, you have to go through those instructions and find the problematic line. This process is known as debugging and it is a feature available in most IDE easily identified by a symbol of a bug.

When learning to program, you are normally required to brainstorm the set of instructions by writing what is known as an algorithm or pseudo code. An algorithm is a general solution that details the unambiguous steps to be followed by the computer to solve the problem.

If you were to write a program to find the average of three numbers, your algorithm would look something like this:
Total = num1 + num2 + num3
Average = total / 3
Print average
The above algorithm can be used in any computer language to find the average of  three numbers. Notice how syntax was not used in the algorithm, this is because an algorithm is computer language independent and its very high level in such a way that anyone can read and understand. An algorithm can have any if not all of these elements namely a steps, decisions and repetitions.

A pseudo code on the other hand is very high level almost English like but it still is computer language independent. One can refer to an algorithm as an intermediate program that can be converted into any computer language really easily. A pseudo code for finding the average of three numbers can look like this:
Add the three numbers together (total)
Divide the total by three (average)
Display the average on the screen
At this point you should note that there are many ways of solving a problem and this means there should be many different algorithms for the same problem. Our pseudo code above assumes that the three numbers are already known. The algorithm can change to ask a user of the program to enter the three numbers.

In computer science, the first program you would normally learn is called hello world which simply just prints the word "Hello, world!" to the screen. Look at the syntax used to create a simple hello world program and compare it to other languages. 
read more

The Python Series

Learn python programming in 12 lessons


When most people hear of Python, they think of the big snake native to most African and Asian countries. For others, Python is one of the most popular high level programming language used today in the industry and academic institutions because of its ease to learn and create code fairly quickly. 
It is mostly common amongst mathematicians, physicist, etc because of its ability to handle big number better than other programming languages such as Java.

Python was created in the late 1980s by a Dutch programmer called Guido van Rossum and he specifically chose to call it Python not after the snake but after a British sketch comedy show called Monty Python.

If you are interested in learning how to write code's, python would be the best language to learn because as powerful as its is, it has the easiest syntax and due to its popularity, you are never going to run out of reference materials.

To start programming in Python, you will need to go to the Python Software Foundation website and get the latest source code, preferably Python 3.* You can still still use Python 2 if you are using a reference book that was written before 2009 which is still going to be OK but for enhanced features and security patches, pick the latest.

The next thing you will need is an Integrated Development Environment known as an IDE and there are a lot of them on the market. Pick the one that is free, small and has a simplified graphical user interface with debugging capability. The debug tool is really important especially for an amateur programmer because it will help you spot part of the code that is producing unwanted results. There are lots of IDE on the market, but you can start with free IDEs such as PyCharm or Wingware.

Programming guru's do not really need IDE, a simple notepad will get the job done and the program is executed via the command line. Whilst we are talking about notepad, you might also want to get yourself Notepad++ and Sublime Text  to use when you reach the point where you can code without an IDE.

One of the most important resource you are going to need is a reference book to help you understand some of the concepts better. A hard copy book is important because it will still be able to guide you way better especially in cases where you have no access to the internet to look up concepts that are bothering you. If you cannot find a good book in your local bookstore, look at getting anyone of these books from Amazon.
  1. Learning Python by Mark Lutz
  2. Python Programming for Begginers by Jason Cannon
  3. Python programming by John Zelle
That's pretty much all you need to start learning programming concepts by using Python. Click and bookmark the label The Python Series to see all posts related to Python. This series of post won't cover the hardcore stuffs, just the basics to get you interested in programming with Python.
read more