Enroll here for April Bootcamp
Live classes, hands-on experience, projects, and certificate
Python Programming
INTRODUCTION
What is Python?
Python is the fastest-growing programming language. It consistently ranks among the top 3 on surveys.
There are others programming languages like Java and C++.
Python is a general-purpose, high-level interpreted language with easy syntax and dynamic semantics.
It was developed by Guido Van Russum in 1989
Who uses Python?

What is Python used for?
- Create websites because it has libraries for internet protocols like HTML and XML, JSON, email processing, FTP, IMAP.
- Desktop GUIs app development using inbuilt modules such as Tkinter as well as web applications using third party libraries such as Django, Flask
- Science and Numeric applications with the use of Scipy, Pandas, IPython, Numpy
- Software development: software developers make use of Python as a support language. Scons, Buildbot, Apache Gump, Roundup, Trac
- Games and 3D graphics
- Data analysis, Artificial intelligence and Machine Learning
- Database access
Why use Python?
• It works on different platforms such as Windows or Mac, or even Linux, Raspberry Pi
• The syntax is close to English language and contains no semicolons or curly brackets. Compare the two ways of printing a simple statement using C++ and Python as shown below. Which is easier?

• Developers like Python because they achieve same results as other languages but with fewer lines of code
How do you use Python?
To begin coding in python, download the software from www.python.org

OPERATORS
Arithmetic Operators
Maths | Python |
---|---|
2 + 3 = 5 | 2 + 3 |
5 x 6 | 5 * 6 |
17 / 6 | 17 / 6 |
quotient of 17 / 3 | 17 // 3 |
remainder of 17 / 3 | 17 % 3 |
divmod (24, 6) will return (4, 0), that is, the quotient and the remainder. It is similar to (a//b, a % b)
# Code to show operators
a = 2 + 3
print (“The sum of 2 and 3 is”, a)
b = 5 * 6
print (“The product of 5 and 6 is”, b)
c = 17/6
print (“The result of 17 divided by 6 is”, c)
d = 17//3
print (“The quotient when 17 divides 3 is”, d)
e = 17 % 3
print (“The remainder when 17 divides 3 is”, e)

Assignment Operators
a = 3 assign or equate 3 to a
a += 3 add and assign to a
a -= 3 subtract and assign to
a *= 3 multiply and assign to
a /= 3 divide and assign to
a %= 3 get the remainder and assign to a
# Assignment Operators
a = 2
print (“Initial value of a is”, a)
a += 3
print (“After adding 3, we get”, a)
a -= 3
print (“After subtracting 3, we get”, a)
a *= 3
print (“After multiplying by 3, we get”, a)

Comparison Operators
> is greater than
< is less than
== is equal to
!= is not equal to
>= greater than or equal to
<= less than or equal to
# Comparison Operators
x = 2
y = 3
print (“Is y greater than x?”, y > x)
print (“Is x greater than y?”, x > y)
print (“Are x and y equal?”, x == y)

# Comparison Operators
p = 25
q = 50/2
r = 5**2
print (“Are p and q equal?”, p == q)
print (“Perhaps q is not equal to r:”, q != r)
print (“I believe p is greater than or equal to r:”, p >= r)

Logical Operators: and/or/not
OR operator


A | B | C |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
AND Operator


A | B | C |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
NOT Operator


A | C |
0 | 1 |
1 | 0 |
Logical operators are usually used with conditional statements
# logical operators
# They are usually used with conditional statements p = 2
q = 7
print (“Is p greater than 1 AND less than 5?”, p > 1 and p < 5)
print (“Is q greater than 4 OR less than 2?”, q > 4 or q < 2)
Absolute and Boolean Operators
abs means
absolute value abs (-43) = 43
bool (0) and bool (none) returns False. All others return True
Membership operators: in / not in
They are used to check if an element belongs to a given set.
The values returned are True or False
# membership operators
fruits = [“apple”, “banana”, “carrot”]
print (“Is banana in fruits?”, “banana” in fruits)
print(“Is mango in fruits?”, “mango” in fruits)

DATA TYPES
• Numbers: integer, float, complex
• Boolean
• String
• List
• Tuples
• Dictionaries
• Sets

STRINGS
They are enclosed in a single or double quotes. a = “Python”
Strings can be counted, with the first character having index = 0.
Length = 6

# strings
a = “Python”
b = “Hello, World!”
print (“The first character in string a is:”,a[0])
print (“The last character in string ais:”, a[-1])
print (“The number of characters in string a is:” ,len(a))

We use square brackets to slice strings
str[index]
str[start : stop]: returns the string between the startindex and stop index
str[start : stop : step]: returns the string between the start and stop index in steps
# strings
c = “iPrep Educational”
print (“The string between the 2nd and 8th characteris:”, c[2:8])
print (“The string btw the 3rd & 15th character skipping one is:”, c[3 : 15: 2])
print (“The string from beginning to the 7th character is:”, c[:7])
print (“The string from the 4th character to the end is:”, c[4:])
print (“The string btw the 5th & the 3rd to the last character is:”, c[5:-3])

i | P | r | e | p | E | d | u | c | a | t | i | o | n | a | l | |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
Strings
str.capitalize() returns the string with the first character of the first word capitalized and the rest in lower case
str.replace (“string”, “replacement”) will replace a string with another string
str.casefold() /str.lower() returns the string in lowercase
str.title() returns the string where each word begins with a capital letter str.upper() returns the string where each word is in uppercase
str.swapcase() returns a copy of the string with uppercase characters converted to lowercase and vice versa
#strings
d = “This is a Python Tutorial”
print (“First letter capitalized and others in lowercase:”, d.capitalize())
print (“Replacing letter ‘a’ with ‘the best’:”, d.replace(‘a ’, ‘the best ’))
#notice the space after the ‘a’ to avoid affectingthe ‘a’ in Tutorial print (“In lowercase:”, d.lower())
print (“in uppercase:”, d.upper())
print (“lower case and uppercase swapped:”,d.swapcase())

str.format() will perform a formatting operation on replacement fields delimited by {}.
Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument
“The sum of 1 + 2 is {0}”.format (1+2)
str.format(age) will insert the age andreturn result as a string str = “Dipo is{age} years old” *show these codes*
Multiple formating is allowed
qty = 8
price = 500
myorder = “I want {}pieces of items for {}” print (myorder.format(qty, price)
# strings
e = “John is {} years old while Kelly is {}”
f = “John is {age_J} years old while Kelly is{age_K}”
print (e.format(2, 10))
print (f.format (age_J = 2, age_K = 10))

We can count the number of times a character appears in a string within a given a range
“James is too good”.count(“o”) returns 5 “James is too good”.count (“o”, 1,15) returns 3
We can also find the position of the first time a given character appears in a string by using the .find() or.index() methods
“James is too good”.find(“o”, 0, 20) returns 10
If we want to split the words in a string, we use the.split() and use sep as the delimeter string
“James is too good”.split(sep = “ ”) returns [“James”,“is”, “too”, “good”]
Working backwards, we can use the “seperator”.join(iterable)” to convert a list to a string and puts the separator string in between the items
“ ”.join([“James”, “is”, “too”, “good”]) will return “James is too good”
str.strip() removes whitespace before and after the string or whatever is specified in the bracket
“ removes whitespace ”.strip() will return ‘removeswhitespace’
# The % operator in a string object
print (“%(language)s has %(number)03d quote types”
%{“language” : “Python”, “number” : 2})

LISTS
The list is probably the most versatile datatype in Python. Characteristics
• Ordered: they can be indexed
• Mutable: the elements can be modified after it is created
• Homogenous (or heterogenous) data: they can contain numbers, strings, or even another list
• Allows duplicate
List may be thought of like a plate rack. They can be created using
[ ], list (iterable), [x for x in range(10)]
#creating lists
fruits = [“apple”, “banana”, “carrot”]
print (fruits)
a = [ ]
#empty list created
print (type(a))
#asking Python for the datatype of a
students = (“Ali”, “Benjamin”, “Casper”)
print(list(students))
b = [x for x in range (10)] print (b)

Look at this list we created
L = [15, “Mike”, 23.75, [20, 40, 60]]
Length = 4

list.append (x): add an item to the end of a list equivalent to a[list(a):] = [x]
list.extend (t): extends list with the contents of another list t
You can also add any iterable such as tuples, sets and dictionaries using this extend
list [i : j] = iterableT slice of list from i to j is replaced by the contents of the iterable T
#list methods
fruits = [“apple”, “pawpaw”, “banana”, “orange”, “mango”, “banana”]
print (“The number of items in thelist is:”, len(fruits))
print (“The item in the third position is:”, fruits [2])
print (“The first 3 items are:”,fruits[ : 3])
print (“How many times can we find banana?”,fruits.count(‘banana’))

You can change the items in a list by referring to a range
fruits[2:3] = [‘apple’, ‘pawpaw’, ‘orange’, ‘pineapple’] will insert the new list in the third position
fruits[2:3] = ‘mango’ will put it as [‘apple’, ‘pawpaw’, ‘orange’, ‘m’,’a’,’n’,’g’,’o’, ‘pineapple’]
list.insert (i, x): insert an item in a given position. Thei is the position of the element before which to insert
list.remove (x): remove the first item from the list whose value is x.
list.copy(): creates ashallow copy of list. newList =oldList.copy()
list.pop(i): remove the item from the list and return it. Ifno index is specified, it removes the last item
list.clear () empties the list. The list still remains but has no contents
#list methods
fruits = [“apple”, “pawpaw”, “banana”, “orange”, “mango”, “banana”]
#let’s add grape to the fruits
fruits.append (‘grape’)
print(fruits)

#Then let’s insert lemon between the pawpaw and banana
fruits.insert (2, ‘lemon’)
print (fruits)

#Why don’t we take out mango
fruits.remove (‘mango’)
print (fruits)

#make a copy of the list of fruits
new_fruits = fruits.copy()
print (new_fruits)

#And then let’s clear the old list
fruits.clear()
print (fruits)

#list methods
students_A = [‘Mike’,‘Helen’, ‘David’]
students_B = [‘Stacy’,‘Henry’, ‘Paul’]
students_A.extend(students_B)
#adding one list to another
print (students_A)

students_A [1:1] = students_B
#adding one list to another by index
print (students_A)

#list methods
fruits = [‘orange’, ‘banana’, ‘pawpaw’, ‘apple’]
numbers = [4, 15, -3, 7]
fruits.sort() #arranges the fruits alphabetically
numbers.sort() #arranges the numbers in ascending order
print (fruits)
print (numbers)

The .sort() method can take two arguments – key and reverse
fruits.sort(key = None, reverse = True)
You can also reverse a list using .reverse()
del listName[0] will remove the first item but del listName will delete the list entirely
list.index (x[, start[, end]]) index of the first occurence of x in list (at or after start index and before end index
list.count (x) total number of occurences of x in list list.sort(key = none, reverse = False)
e.g. numbers = [2, 6, 3, 18]
numbers.sort(reverse = True) will give 18, 6, 3, 2
e.g2
def myfunc(n):
return abs(n)
numbers = [100, 50, 65, 82, 23]
numbers.sort(key = myfunc) print(numbers)
RESULT: [50, 65, 23, 82, 100]
By default, the listName.sort() is case sensitive, that is, it will sort out items that begin will a capital letter before items in small case. if you want it to be case insensitive, use the key = str.lower
list.reverse (): reverses the items of list in place
list comprehension consists of brackets containing an expression followed by a ‘for’ clause, then zero or more for or if clauses
fruits = [‘apple’, ‘banana’, ‘pawpaw’]
[print (x) for x in fruits]
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x!=y]
newlist = [expression FOR item IN iterable IF condition == True]
TUPLES
• They are immutable: You cannot change them but only redefine them.
• They do not support item assignment
•T hey are usually used to store heterogenous data
VarName = (‘item1’, 31, ‘item2’)
They can be constructed using ( ), (a, b, c), tuple(iterable)
Tuples don’t have the inbuilt .append( ) function. However, if you want to add items to a tuple, you can
1. convert it to a list, add, and convert back to tuple
2. add tuple to tuple
unpacking a tuple
fruits = (‘apple’, ‘orange’, ‘cherry’)
(green, yellow, red) = fruits
DICTIONARY
Dictionaries are ordered, changeable datatypes that do not allow duplicates
Ordered means the items have a defined order and can be referenced by an index.
car = {‘brand’ :‘Toyota’, ‘model’ : ‘Corolla’} Notice the use of curly braces
{key: value} makes an item
So you can construct a dictionary using {key : value} like the example above, or
car = dict([(‘brand’, ‘Toyota’), (‘model’,‘Corolla’)])
car[‘colour’] = ‘black’ will add a new item to the dictionary
.items() will return each item in a dictionary as a list
Use DictName.update (DictName2) to add items to a dictionary
car.pop (‘model’) will remove the item specified by the key car.popitem() removes the last item
VarName = {‘Var1’:15, ‘Var2’:20}. DictName.values(), DictName.keys (), Using for loop will return just the keys
for x in car:
print (x)
for x, y in car, items():
This will loop through keys and values
print (x, y)
for b in car:
print (car[x]) will return values
#dictionary methods
car_1 = {‘brand’: ‘Toyota’, ‘model’: ‘Corolla’}
car_2 = {‘brand’: ‘Kia’, ‘model’: ‘Rio’}
#let’sretrieve the model of car_1
print (car_1[‘model’])

#let’s add another key-value pair to car_1
car_1[‘year’] = 2015
print (car_1)

#how do we get the items
print (car_1.items())

#Let’s get the keys and values separately
print(car_1.keys())
print (car_1.values())

Nested Dictionaries
myFamily = {‘child’: {‘name’: ‘dipo’, ‘year’: 2005},‘child2’:{‘name’: ‘Akin’, ‘year’: 1983} }
SETS
A set in Python is
• an unordered collection, which means you can’tindex them
• unique with no duplicate elements.
• changeable.
Sets can be used to test for membership and removing duplicates
Curly brackets {} or the set ( )function can be used to create sets.


#set methods
A = {‘blue’, ‘green’, ‘yellow’, ‘green’} B = set (‘string’)
C = set ([3, 2, 6])
print (A)
print (B)
print (C)

Did you notice the duplicate element was removed when it printed set A?
You can add an element to a set using .add( ). For example, A.add (‘purple’) will add purple to the set A
#set methods
X = {2, 4, 6, 8, 10, 12, 14}
Y = {1, 2, 3, 6, 9, 18}
print (“The union of both sets is”, X | Y)
print (“Intersection (common elements) of both set is”, X & Y)
print (“Elements in X but not in Y are”, X – Y)
print (“Elements in X or Y but not in both include”, X ^ Y)

CONDITIONAL STATEMENTS
IF/ELSE Statements
These usual coding statements are used to make decisions only if a certain condition is satisfied
if test expression:
statement(s)
comparison operators (> < >= <= == !=) are very often used with if/else statements.
A colon is added at the end of the if, elif and else statements
Also, you will see that Python relies on indentation to define the scope of a code just the way other programming languages use curly brackets.

#if/else statements
a = 33
b = 15
if a > b:
print (“a is greater than b”)

age = 16
if age >= 18:
print (“You are eligible to vote”) else:
print (“You are not up to the required age to vote”)

You can combine multiple conditions using elif keyword
if test expression:
statement
elif test expression:
statement(s)
else:
statement
#if/else statements
movie_cost = 2000
age = int (input (“Enter your age: “))
if age <= 12:
print (“Discounted for children. Pay”, 3/5 * movie_cost)
elif age >= 60:
print (“Discounted for senior citizens. Pay”, 1/2 * movie_cost)
else:
print (“Pay”, movie_cost)

FOR – WHILE loops
while loop executes as long as the condition remains true
while condition:
statement(s)
#While loop
x = 1
while x <= 5:
print (“Hello from the while loop”, x)
x += 1
print (“Goodbye from the while loop”)

For loops execute a sequence of statements multiple times depending on the iterable (range, list, string, tuple, dictionary):

#for loop
fruits = [‘apple’, ‘banana’, ‘pineapple’, ‘orange’]
for k in fruits:
print (k, len(k))

Range Function
The range ( ) function generates an arithmetic progression
range (n)
range (start, stop, step)
Note that the last number is never printed
Python Code | Output |
for i in range(5): print (i) | 0, 1, 2, 3, 4 |
for i in range (1, 7): print (i) | 1, 2, 3, 4, 5, 6 |
for i in range (1, 7, 2): print (i) | 1, 3, 5 |
list (range(4)) gives you the values [0, 1, 2, 3]
sum (range(4)) finds the sum of the first 4 numbers starting from 0, and it gives 10
Loop Control Statements
break tells the machine to leave the loop enclosing for or while loop
continue goes on with the next iteration of the loop. It will bypass any code written under it
pass is like a filler statement – it doesn’t do anything
next (iterable, default)
default is an optional parameter. It is returned when there is no next item and the iterator is exhausted
#break, continue and pass
for attempt in range (1, 4):
attempts_remaining = 3 – attempt
password = input(“Enter your password: ”)
if password == “python”:
print (“Correct password \n unlocking your device”)
break
print (“incorrect password \n attempts remaining = ”, attempts_remaining)
With the ‘else’ statement in a while/for loop, we can continue with a block of code once the condition is no longer true or when the loop has ended.
Nested loops
You can have a loop within a loop. The inner loop will be executed first before the outer loop
#break, continue and pass
a = int (input(“Enter the lower limit: ”))
b = int (input(“Enter the upper limit: ”))
for i in range (a, b):
for n in range (2, i):
if i % n == 0:
break
else:
print (i, “is a prime number”)
try and except
The try block allows you to test a block of code for errors. The except block lets you handle the error
They can be used to check the user hasn’t typed anything wrong.
while True:
try: x = int (input (“Enter number”))
break
except ValueError: print (“Oops. Incorrect”)
It may be used to check internet connection
The raise statement allows the programmer to force a specified exception to occur
#try and except
try:
print (a)
except:
print (“An error exception occurred for not defining a”)

FUNCTIONS
A function is a block of code that runs when it is called. The keyword def introduces a function definition.
It must be followed by the function name and the list of parameters in bracket, then a colon(:).
def functionName (pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
The parameter is the variable inside a function while an argument is the value sent to the function.
A function definition looks like
def dog (Bingo, type = “Pitbull”):
A function must be called with the correct number of arguments
You can have
- 2 positional arguments,
- positional & keyword argument,
- 2 keyword arguments
but you cannot have a positional argument after a keyword argument.
If the number of keywords are unknown, add * before the parameter
def name (*kids):
print (‘Hello’ + kids[2])
name (‘Akin’, ‘Bayo’)
If you call a function without an argument, it uses the default value (specified by the parameter).
A function can call itself (recursion)
Global and Local Variables
Variables that are created outside of a function are called global variables. Local variable cannot be called outside a function
To create a global variable inside a function, use the global keyword
def myfunc():
global x
x = fantastic
#global and local variables
x = “This is a global variable”
def check():
x = “This is a local variable”
print (x)
check()

Python Lambda Function
It is quick way to write a small, one-line function
lambda arguments:
expression
It may be used as an anonymous function inside another function
inc = lambda a: a + 1
print (inc(1))
is equivalent to
def inc(a):
return a+1
print (inc (1))
people = [‘Dr. Akin Fada’, ‘Dr. Lawal Oyene’, ‘Dr. Oke Onianwa’, ‘Dr. Dipo Daboiy’]
def splitNames (person):
title = person.split()[0]
lastName = person.split()[-1]
return ‘{}{}’.format (title, lastName)
list (map(splitNames, people))
def splitNames2(person):
return person.split()[0] + ” ” + person.split()[-1] for person in people:
print (splitNames2(person) == (lambda x: x.split()[0] + ‘ ‘ + x.split()[-1](person))
CLASSES
A class is used to define the characteristics of an object (fields and properties) and the things it can do (methods).
It is collection of methods and variables under a common name. Class provide a means of bundling data and functionality together.
A namespace is a mapping from names to objects
class ClassName:
statement1
statement2
Class objects supports two kinds of operation: attributes references and instantiation
An attribute may simply be any name following a dot. E.g.
z.real
real is an attribute of the object z.
often the first argument of a method is self
Class variables are for attributes and methods shared by all instances of the class
instance variables are unique to each instance.
An instance is the class object that is created at run time. It can be called the physical manifestation of a class. An instance is created when a class is assigned to a variable.
An object is the actual thing made using the blueprint (class) and the instance is the virtual copy of that object.
A method is a function that belongs to an object. A constructor (init) is a special type of method that Python calls when it creates an object/instance.
If you create a class called student, you expect it to have related variables like Serial_No, School, Age. Stock price, average rainfall will ruin the point of having a class.
Classes help with reusability. You can call the same methods defined in another class
They also help with maintainability because you use less lines making it easier to debug. You can make custom exceptions to your classes
Inheritance is the concept of having a class inherit properties from another class.
class Inheritance
class DerivedClassName (BaseClassName):
Encapsulation
This is the concept of restricting the direct access of variables and methods. It only allows the object itself to change its variable, just to avoid any accidental change. We call such variables private or protected.
PROTECTED – can only be accessed by the class itself, or its sub-classes. You declare a protected member by using a single underscore _ as preficx
PRIVATE – only accessed by the main class itself. You use a double underscore as prefix.
MODULES
Modules are libraries that hold functions, Python definitions and statements.
It can contain executable statements
The file name is the module name with the suffix .py appended and saved in the current directory.
To use a module, you need to import the contents
import module_name
Random module
import random
It provides tools for making random choices
random.sample / random.choice / random.randrange/random.random
Randint
Randbytes
Shuffle
uniform
math module
import math
sin/cos/tan/pi/radians/degree/log
Statistics
Mean/median/mode/quantiles, variance, correlation
Time, datetime
import time
os module
import os
This module allows us to use the functionalities of the operating system.
json module
Json stands for JavaScript Object Notation) is a lightweight data interchange format
import json
json.dumps (given_list or given_dict or given_tuple or given_string)
stands for dump string. This will modify a Python dictionary to a JSON string
Note that keys in key-value pairs of JSON are always of the type str.
json.load() accepts the file object, parses the JSON data, populates a Python dictionary with the data
json.loads(given_json) stands for load string. It takes in the file content and not the file path as a string and returns a Python dictionary
csv module
Comma Separated values format is the most common file type for spreadsheets and databases
import csv
with open(‘csv_name.csv’, newline =‘’) as variable_name:
reader_name = csv.reader (variable_name, delimiter =‘’, quotechar = ‘|’))
#for loop
with open(‘csv_name.csv’, ‘w’, newline =‘’) as variable_name:
writer_name = csv.writer (variable_name, delimiter =‘’)
writer_name.writerow(string)
DictReader: after reading the file,
#for row in reader:
print (row[‘first_name’], row[‘last_name’])
DictWriter : after writing
columns_list = [column_names]
writer = csv.DictWriter(csvfile, fieldnames = column_list)
writer.writeheader()
writer.writerow({‘first_name’: ‘James’, ‘last_name’: ‘Bond’})
turtle module
import turtle
tkinter module
import tkinter
Third Party Modules
pandas, numpy, matplotlib are commonly used packages for data analysis, manipulation and presentation
Django, flask are used to create websites and develop web software
Pygame is used to create video games
NLTK (Natural language tool kit) is used for processing language data
WHAT’S NEXT?
With Python you are equipped to gain understanding in
- Data Science
- Machine Learning
- Deep Learning