0% found this document useful (0 votes)
15 views59 pages

CCS3255 CourseNotes

CDS 3255 Interactive Programming I is a course designed to introduce students to Python programming, focusing on object-oriented programming, data storage, and manipulation. The course includes various topics such as variables, decision-making, functions, and file handling, with assessments comprising continuous assessment (30%) and examination (70%). Core and recommended reading materials are provided to support learning, along with a structured lesson plan covering essential programming concepts.

Uploaded by

kwambokaw734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views59 pages

CCS3255 CourseNotes

CDS 3255 Interactive Programming I is a course designed to introduce students to Python programming, focusing on object-oriented programming, data storage, and manipulation. The course includes various topics such as variables, decision-making, functions, and file handling, with assessments comprising continuous assessment (30%) and examination (70%). Core and recommended reading materials are provided to support learning, along with a structured lesson plan covering essential programming concepts.

Uploaded by

kwambokaw734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

CDS 3255 INTERACTIVE PROGRAMMING I

Pre-requisite Object Oriented Programming

Purpose of the Course

This purpose of the course is to provide an introduction to Python


programming language in preparation for more advanced programming
courses for large scale data analysis

Expected Learning Outcomes:

1. To experience and use modern object-oriented programming paradigm


2. To understand the principles of data storage and manipulation
3. To get practical knowledge of a popular programming language Python

Course Content:

Introduction: Variables, assignments, Simple input, Main program.


Decision-Making: If-statement, Logical operators. Loops, Output formatting.
Functions: Parameters, return values, Debugger, Lists.
Data Handling: Strings, Dictionary, Values, and references.
Basics of program design: programming style, Exceptions, File handling,
Classes and objects

Mode of Delivery

Face to face Lectures, Group Discussions, Independent Study

Instructional Materials and Equipment

White board, Projectors, E-content

Course Assessment

Continuous Assessment 30%


Examination 70%
Total 100%

Core Reading Materials

1. Charles Severance (2014), Python for Informatics: Exploring Information

2. Allen B. D, Think Python: How to Think like a Computer Scientist.

Recommended Reference Materials

1. Tony Gaddis (2015), Starting Out with Python (Third Edition). Pearson,
New Jersey ISBN:978-0-133-58273-4
2. Swaroop C H. P (2012). A Byte of Python. Creative Commons License

A. Irungu
Lesson Plan
Lesson 1: Introduction

Lesson 2: Variables & Assignments

Lesson 3: Operators

Lesson 4: Decision-Making: If-statement

Lesson 5: Loops

Lesson 6: Functions

Lesson 7: Modules

Lesson 8: Classes and objects

Lesson 9: Exceptions Handling

Lesson 10: File handling

Lesson 11: Data Handling: Strings, Lists, Tuples, and Dictionary

Lesson 12: GUI & CGI Programming (Group Project)

A. Irungu
Table of Contents
Lesson 1: Introduction ................................................................1

Installing Python .................................................................................. 2

Starting Python .................................................................................... 2

Identifiers ........................................................................................... 3

Reserved Words ................................................................................... 3

Indentation / Blocks .............................................................................. 3

Quotations .......................................................................................... 3

Comments ........................................................................................... 4

Statements.......................................................................................... 4

Lesson 2: Variables, assignments, & Simple input .......................1

Data Types .......................................................................................... 1

Data Type Conversion ........................................................................... 3

Assigning Values to Variables ................................................................. 4

Assigning Values from User Input ............................................................ 4

Lesson 3: Operators in Python .......................................................1

Types of Operators ............................................................................... 1

Operator precedence ............................................................................. 2

Lesson 4: Decision Structures........................................................1

if statement ......................................................................................... 1

if... else statements .............................................................................. 2

elif Statement ...................................................................................... 2

Nested if statements ............................................................................. 3

Single Statement .................................................................................. 3

Lesson 5: Loops .............................................................................1

while Loop Statements .......................................................................... 1

for Loop Statements ............................................................................. 2

Using else Statement with Loops ............................................................. 2

Single Statement Loops ......................................................................... 3

A. Irungu
Loop Control Statements ....................................................................... 3

Iterator and Generator .......................................................................... 5

Lesson 6: Functions .......................................................................1

Function Definition ................................................................................ 1

Calling a Function ................................................................................. 1

Pass by Reference vs Value .................................................................... 1

Function Arguments .............................................................................. 2

Anonymous Functions ........................................................................... 4

Return Statement ................................................................................. 4

Scope of Variables ................................................................................ 4

Namespaces and Scoping ....................................................................... 5

Lesson 7: Modules .........................................................................1

import Statement ................................................................................. 1

from...import Statement ........................................................................ 1

Executing Modules as Scripts .................................................................. 2

Locating Modules .................................................................................. 3

The dir( ) Function ................................................................................ 3

The globals() and locals() Functions......................................................... 3

The reload() Function ............................................................................ 4

Packages in Python ............................................................................... 4

Assignment: ........................................................................................ 5

Lesson 8: Object-Oriented Programming in Python .......................1

OOP Concepts in Python ........................................................................ 1

Creating Classes..................................................................................... 1

Creating Instance Objects ........................................................................ 2

Accessing Attributes ............................................................................... 2

Built-In Class Attributes ........................................................................... 3

Destroying Objects (Garbage Collection)........................................................ 3

Class Inheritance ................................................................................... 4

ii

A. Irungu
Overriding Methods .................................................................................. 6

Base Overloading Methods ........................................................................... 6

Overloading Operators ............................................................................... 6

Data Hiding (Private data members) .......................................................... 7

Lesson 9: Exceptions Handling ......................................................1

Standard Exceptions ................................................................................. 1

Assertions in Python ................................................................................... 2

What is Exception? .................................................................................... 3

Handling an Exception ............................................................................... 3

The except Clause with No Exceptions .............................................................. 4

The except Clause with Multiple Exceptions ....................................................... 4

Argument of an Exception ........................................................................... 5

Raising an Exception.................................................................................. 6

User-Defined Exceptions ............................................................................. 7

Lesson 10: File handling .............................................................1

Printing to the Screen ................................................................................. 1

Reading Keyboard Input ............................................................................ 1

Opening and Closing Files ........................................................................... 1

Reading and Writing Files ............................................................................ 3

Renaming and Deleting Files ......................................................................... 4

Directories in Python .................................................................................. 4

File & Directory Related Methods .................................................................... 4

Lab Exercises: Using Strings, Lists, Tuples, and Dictionary............9

References .................................................................................. 10

iii

A. Irungu
Lesson 1: Introduction
Python is a high-level, interpreted, interactive and object-oriented
programming language. Python is designed to be highly readable. It uses
English keywords frequently whereas the other languages use punctuations. It
has fewer syntactical constructions than other languages

The current version of Python (3.x) was released in 2008. This version is not
compatible with the prior version (2.x). This course will be based on the syntax
of Python version 3.x.

Interpreted: Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it. This is similar to PERL and
PHP.

Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

Object-Oriented: Python supports Object-Oriented style or technique of


programming that encapsulates code within objects.

Python's features include-

 Easy-to-learn: Python has few keywords, simple structure, and a clearly


defined syntax. This allows a student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the
eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable
and cross- platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode, which
allows interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries and windows systems,
such as Windows MFC, Macintosh, and the X Window system of Unix.

A. Irungu
 Scalable: Python provides a better structure and support for large
programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good
features. A few are listed below-

 It supports functional and structured programming methods as well as


OOP.
 It can be used as a scripting language or can be compiled to byte code for
building large applications.
 It provides very high-level dynamic data types and supports dynamic type
checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Installing Python

Discuss in groups and find out the best way / form of python installation

Starting Python

There are three different ways to start Python-

1. Interactive Interpreter

You can start Python from a command-line interpreter or shell window. This is
achieved by executing the python command from a shell prompt. Then you
can start coding right away using the interactive interpreter.

2. Script from the Command-line

A Python script can be executed at the command line by invoking the


interpreter on your application. Eg C:>python test.py # Windows/DOS

While on Linux /Unix platforms always ensure the file permission mode allows
execution.

3. Integrated Development Environment

You can run Python from a Graphical User Interface (GUI) environment as well,
if you have a GUI application on your system that supports Python. Examples
are PyCharm, Visual Studio Code, Sublime Text, Vim, Atom, Jupyter
Notebook, Eclipse + PyDev + LiClipse, GNU Emacs, Spyder, Thonny.

A. Irungu
Identifiers
A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to
9). Punctuation characters such as @, $, and % are not allowed within
identifiers. Python is a case sensitive programming language.

Here are naming conventions for Python identifiers-

• Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with two leading underscores indicates a strong
private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language- defined special name.

Reserved Words
and, as, assert, break, class, continue, def, del
elif, else, except, exec, finally, for, from, global,
if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while, with, yield

Indentation / Blocks

Python does not use braces ({}) to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line
indentation, which is rigidly enforced.

gender="Male"
if gender=="Male":
print ("Gender is Male")
print ("do something …")
else:
print ("Not Male")
print ("do a different …")
Quotations

Single, double, and triple (''' or """) quotes are used to denote string literals,
as long as the same type of quote starts and ends the string. Eg.

word = 'word'

A. Irungu
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up of multiple lines and
sentences."""

Comments

A hash sign (#) that is not inside a string literal is the beginning of a comment.
All characters after the #, up to the end of the physical line, are part of the
comment and the Python interpreter ignores them.

e.g. # My First comment

Statements

Statements in Python typically end with a new line. The semicolon (;) allows
multiple statements on a single line. The line continuation character (\) allows
one statement to break to the next line. However, statements contained within
the [], {}, or () brackets do not need to use the line continuation character.

A. Irungu
Lesson 2: Variables, assignments, & Simple input
Variables are nothing but reserved memory locations to store values. It means
that when you create a variable, you reserve some space in the memory.

Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to the variables, you can store integers, decimals or
characters in these variables.

Data Types

Python has five standard data types-

a) Numbers (integers, float, and complex numbers)


b) String
c) List
d) Tuple
e) Dictionary

Numbers

Number data types store numeric values. They are immutable data types. This
means, changing the value of a number data type results in a newly allocated
object. Number objects are created when you assign a value to them.

Homework:

Practice using mathematical functions on numbers

Strings

A string as a contiguous set of characters represented in the quotation marks.


Python allows either pair of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 to the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example-

name = 'Meru # Assign a string literal to a variable


University'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + " # Prints concatenated string

A. Irungu
Library")

Homework:

Practice using string functions & operations

Lists

A list contains items separated by commas and enclosed within square


brackets ([]). To some extent, lists are similar to arrays in C. One of the
differences between them is that all the items belonging to a list can be of
different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to
end -1. The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator. For example-

List = ['peter', 22, 7.5, # Create a list


'cow']
fruits = ['lemon', 'bananas'] # Create a second list
print (list) # Prints the first list
print (list[0]) # Prints the first element of first
list
print (list[1:3]) # Prints elements of the first list,
starting from 2nd till 3rd
print (list[2:]) # Prints elements of the first list
starting from 3rd element
print (list * 2) # Prints the first list twice
print (list + fruits) # Prints concatenation of the two lists

Homework:

Practice on list functions & operations

Tuples

A tuple is sequence data type consisting of a number of values separated by


commas.

The main difference between lists and tuples is while elements in a lists are
enclosed in brackets ( [ ] ) and their elements and size can be changed, while
elements in a tuple are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be considered as read-only lists. For example-

tuple = ('peter', 22, 7.5, # Create a first tuple


'cow')

A. Irungu
fruits = ('lemon', 'bananas') # Create a second tuple
print (tuple) # Prints the first tuple
print (tuple[0]) # Prints 1st element of the first
tuple
print (tuple[1:3]) # Prints elements of the first tuple
starting from 2nd till 3rd
print (tuple[2:] # Prints elements of the first tuple
starting from 3rd element
print (fruits * 2) # Prints of the first tuple twice
print (tuple + fruits) # Prints concatenation of the two
tuples

Homework:

Practice on tuple functions & operations

Dictionary

A dictionary work like associative arrays or hashes, and consist of key-value


pairs. A dictionary key can be almost any data type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary object in Python.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example-

mydict = {'name': 'peter','staffno':1261, 'dept': 'HR'}


print (mydict['staffno']) # Prints value for 'staffno' key
print (mydict) # Prints complete dictionary
print (mydict.keys()) # Prints all the keys
print (mydict.values()) # Prints all the values
Elements in a dictionary are not ordered, or simply put, order is of no
importance!

Homework:

Practice on dictionary functions & operations

Data Type Conversion

To convert between types, you simply use the type-name as a function.

There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted
value.

Function Description
int(x [,base]) Converts x to an integer. The base specifies the base

A. Irungu
if x is a string.
float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,
value) tuples.
chr(x) Converts an integer to a character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space.


The declaration happens automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.

e.g.
name="peter" # A string
num2=100 # An integer
weight=67.50 # A float
isMale=True # A bolean
Python allows assigning of a single value to several variables simultaneously.

e.g. num1=num2=num3=100
or multiple objects to different variables.

e.g. name, num2, weight ="peter", 100, 67.50


Assigning Values from User Input

Python allows assigning a value to a variable from an input entered by a user.

Example

name=input ("Enter your name: ")


The input is always treated as a string. Thus, the input must be converted
before assigning to a different variable type.

Homework:

Practice on date & time functions and operations

Try out the following

import calendar as cal


print (cal.calendar(2022))

A. Irungu
Lesson 3: Operators in Python
Operators are the constructs, which can manipulate the value of operands

Types of Operators

Python supports the following types of operators-

a) Arithmetic Operators
b) Comparison (Relational) Operators
c) Assignment Operators
d) Logical Operators
e) Bitwise Operators
f) Membership Operators
g) Identity Operators

Arithmetic Operators

An arithmetic operation is performed between two operands. The operators are


Addition (+), Substation (-), Multiplication (*), division (/), modulus (%),
exponent (**), and floor (//).

For example, the last 3 operators;

9%2 # The result is 1


9**2 # The result is 81
9//2 # The result is 4

Comparison / Relational Operators

Compare values on either side of the operator and decide if the relation among
them is either true or false. These are equal to (==), not equal to (!=),
greater than (>), less than (<), greater than or equal to (>=), less than or
equal to ( <=)

Assignment Operators

Operator Description Example


= Assigns values from right c = a + b assigns value of a + b into
side operands to left side c
operand
+= Add AND It adds right operand to c += a is equivalent to c = c + a
the left operand and
assign the result to left
operand
-= Subtract AND It subtracts right c -= a is equivalent to c = c - a
operand from the left
operand and assign the
result to left operand

A. Irungu
*= Multiply AND It multiplies right c *= a is equivalent to c = c * a
operand with the left
operand and assign the
result to left operand
/= Divide AND It divides left operand c /= a is equivalent to c = c / a
with the right operand
and assign the result to
left operand
%= Modulus AND It takes modulus using c %= a is equivalent to c = c % a
two operands and assign
the result to left operand
**= Exponent AND Performs exponential c**=a is equivalent to c = c** a
(power) calculation on
operators and assign
value to the left operand
//= Floor Division It performs floor division c //= a is equivalent to c = c // a
on operators and assign
value to the left operand

Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a


= 60; and b = 13; Now in binary format they will be as follows-

a = 0011 1100
b = 0000 1101
a&b = 0000 1100 (AND)
a|b = 0011 1101 (OR)
a^b = 0011 0001 (XOR)
~a = 1100 0011 (unary operation Binary One’s complement)

Logical Operators

Logical Operations evaluate to either true or false. The operators used are
and, or, and not

Membership Operators

Membership operators test for membership in a sequence; such as strings,


lists, or tuples. These operators are in and not in

Identity Operators

Identity operators compare the memory locations of two objects. These


operators are is and is not.

Operator precedence

Operator precedence affects the evaluation of an expression. In the table


below, the operators with the highest precedence appear at the top, while
those with the lowest appear at the bottom.

A. Irungu
Exponentiation (raise to the power)
**
complement, unary plus and minus
~, +@, -@
Multiply, divide, modulo and floor division
*, /, %, //
Addition and subtraction
+, -
Right and left bitwise shift
>>, <<
Bitwise 'AND'
&
Bitwise exclusive `OR' and regular `OR'
^, |
Comparison operators
<=, <, >, >=
Equality operators
<>, ==, !=
Assignment operators
= ,%=, /=, //=, -
=, +=, *=,**=
Identity operators
is, is not
Membership operators
in, not in
Logical operators
not, or, and

A. Irungu
Lesson 4: Decision Structures
Decision structures evaluate multiple expressions, which produce TRUE or
FALSE as the outcome. The following is the general form of a typical decision-
making structure found in most of the programming languages-

Python programming language assumes any non-zero and non-null values as


TRUE, and any zero or null values as FALSE value.

There are three constructs of decision-making statements in Python:

 if statements
 if...else statements,
 nested if statements

if statement

If the conditional expression in an if statement is True, then the block of


statement(s) inside the if statement is executed.

Example 1

age = 20
if age:
print ("Age is true")
print (age)
Example 2

if age < 18:


print ("This is a minor")
print (age)

A. Irungu
if... else statements

An else statement can be combined with an if statement. An else statement


contains a block of code that is executed when the conditional expression in
the if statement is False. The else statement is optional; and there can only be
at most one else statement following an if statement.

Syntax

if expression:
statement(s)
else:
statement(s)
Example

score=int (input ("Enter the score: "))


if score<50:
grade="Fail"
print ("Failed: Score = ", score)
else:
grade="Pass"
print ("Passed: Score = ", score)

elif Statement

The elif statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE;

Syntax

if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example
score=int (input ("Enter the score: "))
if score<40 and score>=0:
grade="F"
elif score<50:
grade="D"
elif score<60:
grade="C"
elif (score<70):

A. Irungu
grade="B"
elif score<=100:
grade="A"
else:
print ("Invalid Score!")
print ("Score = " + str(score) +", Grade = " + grade)

Nested if statements

An if construct can be included as part of statements inside another if


construct.

Syntax

if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
statement(s)
Example
name = input ("Enter your name: ")
if len(name)>5:
print ("Your name has more than 5 characters")
if 'a' in name:
print ("Your name has the vowel a")
else:
print ("Your name does not have the vowel a")
else:
print ("Your name has less than 6 characters")
if 'i' in name:
print ("Your name has the vowel i")
else:
print ("Your name does not have the vowel i")
Single Statement
If the body of an if statement consists of only a single line statement, it can be
written in the same line as the header statement.

Example

if num%3==0:print ("Number is divisible by 3")

A. Irungu
Lesson 5: Loops
A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a flow chart of a loop
statement.

Python programming language provides the following types of looping


constructs

a) while loop
b) for loop
c) nested loops .

while Loop Statements

A while loop statement in Python programming language repeatedly executes a


target statement as long as a given condition is true. It tests the condition
before executing the loop body

Syntax

while expression:
statement(s)
Example

count = 0
while (count < 10):
print ('The count is:', count)
count = count + 1

A. Irungu
for Loop Statements
In Python, the for statement has the ability to iterate over the items of any sequence,
such as a list or a string.
Syntax

for iterator in sequence:


statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterator. Next, the statements block
is executed. Each item in the list is assigned to iterator, and the statement(s) block is
executed until the entire sequence is exhausted.

Example 1

for i in range (10): # using a range of numbers


print(i)
Example 2

name = 'university' # using a string


for letter in name:
print(letter)
Example 3

animals = ['lion', 'buffalo', 'hippo'] # using a list


for animal in animals:
print(animal)
Example 4

animals = ('lion', 'buffalo', 'hippo') # using a Tuple


for animal in animals:
print(animal)

Using else Statement with Loops


Python supports having an else statement associated with a loop statement.

 If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted iterating the list.
 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else
statement gets executed.
num=1
while num !=0:
print (str(num) + " squared = "+ str(num*num))
num= int(input("Enter a number : "))
else:
print (" Number Zero Entered. STOP")

A. Irungu
Single Statement Loops
Similar to the if statement syntax, if a loop consists of a single statement only,
everything can be placed in a single line.
Example:

name = 'university'
for letter in name: print(letter)
Nested loops
A nested loop is a loop that is used inside the body of another loop.

Syntax for nested for loops

for iterator1 in sequence:


for iterator2 in sequence:
statements(s)
statements(s)
Syntax for nested while loops

while expression:
while expression:
statement(s)
statement(s)
Additionally, any type of loop can be nested inside any other type of loop. For
example, a for loop can be inside a while loop or vice versa.

Example: A nested-for loop to display multiplication tables from 1-6.

for i in range(1,6):
for j in range(1,6):
k=i*j
print (k, end='\t')
print()
The print() function inner loop has end=' \t' which appends a tab space
instead of default newline. Hence, the numbers will appear in one row. The
Last print() will be executed at the end of inner for loop.

Loop Control Statements

The Loop control statements change the execution from its normal sequence.
When the execution leaves a scope, all automatic objects that were created in
that scope are destroyed.

break statement - Terminates the loop statement and transfers execution to


the statement immediately following the loop.

A. Irungu
continue statement - Causes the loop to skip the remainder of its body during
the current iteration, and immediately retest its condition
prior to reiterating.

pass statement - It is used when a statement is required syntactically but you


do not want any command or code to execute.

break statement

The break statement is used for terminating of the current loop prematurely.
After terminating the loop, execution resumes at the next statement after the
loop.

Example 1

name = 'university'
for letter in name:
if letter=='r':
break
print(letter)
Example 1

num = 0
while num<10:
if num==6:
break
print(num*num)
num+=1

continue Statement

The continue statement causes the loop to start the next iteration without executing
the remaining statements in the current iteration.

Example 1

name = 'university'
for letter in name:
if letter=='r':
continue
print(letter)
Example 1

num = 0
while num<10:
num+=1
if num==6:
continue
print(num*num)

A. Irungu
pass Statement

It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing
happens when it executes.

for letter in 'university':


if letter == 'v':
pass
print (letter)

Iterator and Generator

Iterators are something that help to loop over different objects in Python.
Iterator goes over all the values in the list. Iterators apply the iterator protocol
that contains basically two methods:

_iter_()
_next_()
Iterable objects are objects which you can iterate upon. Examples of iterables
are tuples, dictionaries, lists, strings, etc.These iterables use iter() method to
fetch the iterator.

Example:

fruits = ('avocado', 'beetroot', 'berries')


myiter = iter(fruits)
print(next(myiter))
print(next(myiter))
print(next(myiter))

A generator is a function that produces or yields a sequence of values using


yield method.

When a generator function is called, it returns a generator object without even


beginning execution of the function. When the next() method is called for the
first time, the function starts executing, until it reaches the yield statement,
which returns the yielded value. The yield keeps track i.e. remembers the last
execution and the second next() call continues from previous value.

Example
square= (x ** 2 for x in range(5))
print (next(square))
print (next(square))
print (next(square))
print (next(square))
print (next(square))

A. Irungu
The following example defines a generator, which generates an iterator for all
the squares up to a given numbers.

import sys
def squares(n): #generator function
counter = 0
while True:
if (counter > n):
return
yield counter**2
counter += 1
sqr = squares(5) #sqr is iterator object
while True:
try:
print (next(sqr))
except StopIteration:
sys.exit()

A. Irungu
Lesson 6: Functions
A function is a block of organized, reusable code that is used to perform a
single, related action. Python has many built-in functions like print(), etc.

In addition to the built-in functions, user-defined functions can also be created.

Function Definition
 Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these
parentheses.
 Parameters can also be defined inside these parentheses.
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
 The code block within every function starts with a colon (:) and is
indented.
 The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments
is the same as return None.

Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and should be passed in the
same order that they were defined.
Example

def calc_area( radius ):


area=3.142*radius*radius
print (area)
return
Calling a Function
Defining a function gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Example

calc_area (7)
Pass by Reference vs Value

A. Irungu
Python utilizes a system, which is known as “Call by Object Reference” or “Call
by assignment”.
Whenever arguments of immutable objects like whole numbers, strings, or
tuples are passed as arguments to a function, the passing is like call-by-value
because their value cannot be changed.
On the other hand, passing of mutable objects like lists, can be considered as
call by reference because their values can be changed inside the function.
Example1: Call by value

def calc_area( radius ):


area=3.142*radius*radius
print ("The area is " + str(area))
radius*=2
return
r=float(input("Enter the radius of a circle : "))
print (r)
calc_area (r)
print (r)

Example1: Call by Reference

def calc_volume( args):


vol=3.142* args [0]* args [0]* args[1]
print ("The volume is " + str(vol) + " cubed")
args[0]*=2
return
dimensions=[7,10]
print(dimensions) # before the function call
calc_volume (dimensions) # first call to the function
print(dimensions) # after the function call

Function Arguments
A function call can be made using the following types of formal arguments-
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required Arguments

Required arguments are the arguments passed to a function in correct


positional order. In this case, the number of arguments in the function call
should match exactly with the function definition.
To call the function calc_volume you must pass two arguments, otherwise a
syntax error will occur.
Example:

A. Irungu
def calc_volume(radius, height):
vol=3.142* radius*radius *height
print ("The volume is " + str(vol) + " cubed")
return
calc_volume (7, 10) # function call using required arguments

Keyword Arguments

When keyword arguments are used in a function call, the caller identifies the
arguments by the parameter name. This allows skipping or placing arguments
out of order because the Python interpreter can use the keywords provided to
match the values with parameters.
Example:
calc_volume (height=10, radius=7) # function call using keyword arguments

Default Arguments

A default argument is an argument that assumes a default value if a value is


not provided in the function call for that argument.

Example:

def calc_volume(radius, height=10):


vol=3.142* radius*radius *height
print ("The volume is " + str(vol) + " cubed")
return
calc_volume (7) # function call using default arguments
calc_volume (7,14) # function call without using default arguments

Variable-length Arguments

Variable-length arguments are used when there is need to process more


arguments than those specified during function definition. Variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
An asterisk (*) is placed before the variable name that holds the values of all
non-keyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call.
def calc_volume(r, *varHeight):
for height in varHeight:
print ("The volume is " + str(3.142* r* r *height) + " cubed")
return
calc_volume(7,10,20,30,40)

A. Irungu
Anonymous Functions
Anonymous functions are not declared in the standard manner; using the def
keyword. The lambda keyword is use do create small anonymous functions.
 Lambda functions can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression.
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
 Although it appears that lambdas are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose purpose
is to stack allocation by passing function, during invocation for
performance reasons.
Syntax

lambda [arg1 [, arg2, ..., argn]]: expression

Example

vol = lambda radius, height: 3.142*radius**2*height # Function definition


in one line
print ("Volume is: ", vol (10, 2)) # a function call

Return Statement

The statement return [expression] exits a function, optionally passing back


an expression to the caller. A return statement with no arguments is the same
as return None.
Example

def calc_volume(r, h):


vol=3.142* r**2*h
return vol
print ("The volume is " + str(calc_volume (10,2)) + " cubed")

Scope of Variables

The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in
Python-

 Global variables
 Local variables

A. Irungu
Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope. Local variables can be accessed only
inside the function in which they are declared, whereas global variables can be
accessed throughout the program body by all functions.

Namespaces and Scoping

Variables are names (identifiers) that map to objects. A namespace is a


dictionary of variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the


global namespace. If a local and a global variable have the same name, the
local variable shadows the global variable.

Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions. Python takes any variable assigned a value
in a function is local. Therefore, in order to assign a value to a global variable
within a function, the global statement must be used. The statement global
VarName tells Python that VarName is a global variable. In which case, python
won’t search the local namespace for the variable.

A. Irungu
Lesson 7: Modules
A module is a Python object with arbitrarily named attributes that you can bind
and reference. It allows for logical organization of Python code which makes
the code easier to use and understand. In a nutshell, a module is a Python file
with definitions of functions, classes and variables. A module can also include
runnable code.

import Statement
A Python source file can be used (imported) as a module by executing an
import statement in some other Python source file. The import has the
following syntax-

import module1[, module2[,... moduleN]

Example

import calendar
print (calendar.calendar(2022))

When the interpreter encounters an import statement, it imports the module if


the module is present in the search path. A search path is a list of directories
that the interpreter searches before importing a module.

Example:

Consider a python source file named hello.py containing the following code;

def sayhi(arg ):
print ('Hello ', arg)
return
The file can be imported into another source file as follows;

import hello
# A call to defined function as follows
hello.sayhi("Peter")

A module is loaded only once, regardless of the number of times it is imported.


This prevents the module execution from happening repeatedly, if multiple
imports occur.
from...import Statement

The from statement is used to import specific attributes from a module into the
current namespace.

Example:

A. Irungu
Consider our hello.py source file with the following code:

def sayhi( arg ):


print ('Hello ',arg)
return
def loop(num):
while num>0:
print (num)
num-=1

A specific module in hello.py can be imported into another source file as


follows;

from hello import loop


# A call to defined function as follows
loop (10)
This statement does not import the entire hello module into the current
namespace; it just introduces the function loop from the module hello into the
global symbol table of the importing module.

The statement from hello import * is used to import all the names from the
hello module into the current namespace. This statement should be used
sparingly.

Executing Modules as Scripts

Within a module, the module’s name (as a string) is available as the value of
the global variable __name__. The code in the module will be executed, just as
if you imported it, but with the __name__. set to "__main__. ".

Add this code at the end of your module-

def fib(n): # return Fibonacci series up to n


result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
if __name__== "__main__":
f=fib(100)
print(f)

A. Irungu
When you run the above code, the following output will be displayed.

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Locating Modules
When you import a module, the Python interpreter searches for the module in
the following sequences-
 The current directory.
 If the module is not found, Python then searches each directory in the
shell variable PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python3/.

The module search path is stored in the system module sys as the sys.path
variable. This variable contains the current directory, PYTHONPATH, and the
installation-dependent /default path.

Example:

What is the current search path?


import sys
for p in sys.path: print(p)
How to add a directory to the current search path

sys.path.append('X:/path/') # where X is a drive letter

The dir( ) Function

The built-in function dir() returns a sorted list of strings containing the names
defined by a module. The list contains the names of all the modules, variables
and functions that are defined in a module.

Example

import hello
dir(hello)

Here, the special string variable __name__ is the module's name, and __file__
is the filename from which the module was loaded.

The globals() and locals() Functions

A. Irungu
The globals() and locals() functions can be used to return the names in the
global and local namespaces depending on the location from where they are
called.

 If locals() is called from within a function, it will return all the names
that can be accessed locally from that function.
 If globals() is called from within a function, it will return all the names
that can be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.

The reload() Function


When a module is imported into a script, the code in the top-level portion of a
module is executed only once.
Therefore, if you want to re-execute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously imported
module again. The syntax of the reload() function is this-
reload(module_name)

The module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do
the following-
reload(hello)

Packages in Python

A package is a hierarchical file directory structure that defines a single Python


application environment that consists of modules and sub-packages and sub-
sub-packages, etc.

Example: How to create a Package

Consider a file factorial.py available in mypack directory, in which a function


called factorial() is defined. A file hello.py file in which a function hello()
defined. And a file loop.py file in which a function loop() defined
Then add one more file __init .py in to the mypack directory.

To make all the functions available when mypack is imported, add explicit
import statements in init .py as follows-
from factorial import factorial
from hello import hello

A. Irungu
from loop import loop

When mypack package is imported to a program.

import mypack as m
m.factorial(6);
m.hello()
m.loop()

In the above example, a single function in defined in each file. However,


multiple functions (or even python classes) can be defined in each file.

Assignment:

Read and Discuss the following ecosystem among your study groups;
Modules
Packages
Libraries
Frameworks

A. Irungu
Lesson 8: Object-Oriented Programming in Python

Python is an object-oriented language, supporting the creating and using of


classes and objects.
OOP Concepts in Python

 Class: A user-defined prototype for an object that defines a set of


attributes that characterize any object of the class. The attributes are
data members (both class variables and instance variables) and methods.
Data members and methods are accessed via dot notation.
 Object: A unique instance of a data structure that is defined by its class.
An object comprises both data members (class variables and instance
variables) and methods.
 Instance: An individual object of a certain class. An object obj that
belongs to a class Shape, for example, is an instance of the class Shape.
 Instantiation: The creation of an instance of a class.
 Data member: A class variable or instance variable that holds data
associated with a class and its objects.
 Class variable: A variable that is shared by all instances of a class. Class
variables are defined within a class but outside any of the class's
methods. Class variables are not used as frequently as instance variables
are. Class variables are similar to static member data in C++.
 Instance variable: A variable that is defined inside a method and
belongs only to the current instance of a class.
 Method: A special kind of function that is defined in a class definition.
 Function overloading: The assignment of more than one behavior to a
particular function. The operation performed varies by the types of
objects or arguments involved.
 Operator overloading: The assignment of more than one function to a
particular operator.
 Inheritance: The transfer of the characteristics of a class to other
classes that are derived from it.

Creating Classes
The class statement creates a new class definition.
Syntax:

class ClassName:
'Optional class documentation string'
class_suite

The class has a documentation string, which can be accessed using;


ClassName.__doc__

A. Irungu
The class_suite consists of all the component statements defining class
members, data attributes and functions.
Example

class Employee:
'Common base class for all employees'
empCount = 0
def __init__ (self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)

The variable empCount is a class variable whose value is shared among all
the instances of this class. This can be accessed as Employee.empCount
from inside the class or outside the class.
The first method __init__ () is a special method, which is called class
constructor or initialization method that is called when a new instance of
this class is created.
Other class methods are defined similar to other normal functions with the
exception that the first argument to each method is self. Python adds the
self argument to the list during a function call such that this first argument
is not required during a call to a member function.
Creating InstanceObjects
To create instances of a class, a call is made to the class using class name,
passing whatever arguments that can be accepted by its init method
accepts.

Example:

emp1 = Employee("Zara", 2000)


emp2 = Employee("Manni", 5000)

AccessingAttributes
The dot operator is used to access the attributes of an object. Class variable
would be accessed using class name as follows-

emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)

Attributes of classes and objects can added, removed, or modified at any time.

A. Irungu
emp1.salary = 7000 # Add an 'salary' attribute.
emp1.name = 'xyz’ # Modify 'age' attribute.
del emp1.salary # Delete 'age' attribute.

Instead of using the normal statements to access attributes, the following


functions can be used-

 The getattr(obj, name[, default]): to access the attribute of object.


 The hasattr(obj,name): to check if an attribute exists or not.
 The setattr(obj,name,value): to set an attribute. If attribute does not
exist, then it would be created.
 The delattr(obj, name): to delete an attribute.

Example:

hasattr(emp1, 'salary') # Returns true if 'salary' attribute exists


getattr(emp1, 'salary') # Returns value of 'salary' attribute
setattr(emp1, 'salary', 7000) # Set attribute 'age' at 8
delattr(emp1, 'salary') # Delete attribute 'age'

Built-InClassAttributes
Every Python class keeps the following built-in attributes and they can be
accessed using the dot operator, just like any other attribute.

__dict__: Dictionary containing the class's namespace.


__doc__: Class documentation string or none, if undefined.
__name__: Class name.
__module__: Module name in which the class is defined. This attribute is "
main " in interactive mode.
__bases__: A possibly empty tuple containing the base classes, in the order
of their occurrence in the base class list.

Destroying Objects (GarbageCollection)

Python deletes unneeded objects (built-in types or class instances)


automatically to free the memory space. The process by which Python
periodically reclaims blocks of memory that no longer are in use is termed as
Garbage Collection.

A. Irungu
Python's garbage collector runs during program execution and is triggered
when an object's reference count reaches zero. An object's reference count
changes as the number of aliases that point to it changes.

An object's reference count increases when it is assigned a new name or


placed in a container (list, tuple, or dictionary). The object's reference count
decreases when it is deleted with del, its reference is reassigned, or its
reference goes out of scope. When an object's reference count reaches zero,
Python collects it automatically.
The garbage collector destroys an orphaned instance and reclaims its space
quietly . However, a class can implement the special method del (), called
a destructor, that is invoked when the instance is about to be destroyed. This
method might be used to clean up any non-memory resources used by an
instance.

Example

This del () destructor prints the class name of an instance that is about to
be destroyed.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3))
del pt1
del pt2
del pt3

Note: Ideally, classes should be defined in a separate file, then imported to


the main program file using import statement.

In the above example, assuming definition of a Point class is contained in point.py


and there is no other executable code in it.
import point as p
p1=p.Point()

ClassInheritance
A class can be created by deriving it from a pre-existing class; listing the
parent class in parentheses after the new class name.

A. Irungu
The child class inherits the attributes of its parent class, whereby the attributes
of the parent can be used as if they were defined in the child class. A child class
can also override data members and methods from the parent.
Derived classes are declared much like their parent class; however, a list of
base classes to inherit from is given after the class name −

Syntax

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite

You can use issubclass() or isinstance() functions to check a relationship of


two classes and instances.

 The issubclass(sub, sup) boolean function returns True, if


the given subclass sub is indeed a subclass of the superclass sup.
 The isinstance(obj, Class) boolean function returns True, if obj is an
instance of class Class or is an instance of a subclass of Class.
Example:

class Employee:
'Common base class for all employees'
def __init__ (self, name, id):
self.name = name
self.id = id
def updatePhone(self, phone):
self.phone = phone
return True
def getById(self, id):
if id == self.__id:
return self
else:
return self
class Developer(Employee): # define child class
def __init__ (self, link):
self.gitHubLink = link
def updateGitHubLink (self, link):
self.gitHubLink = link

class Designer(Employee): # define child class


def __init__ (self, link):
self.DribbleLink = link
def updateDribbleLink (self, link):
self.DribbleLink = link
des1=Designer("john",6)
des2=Designer("john",5)
dev1=Developer("grace",7)
dev2=Developer("susan",9)

A. Irungu
Overriding Methods
Overriding of parent methods is done when a different functionality in desired
in the derived class.
Example

class Parent: # define parent class


def myMethod(self):
print ('Calling parent method')

class Child(Parent): # define child class


def myMethod(self):
print ('Calling child method')
c = Child() # instance of child
c.myMethod() # child calls overridden method

Base Overloading Methods


The following table lists some generic functionality that can be overridden.

SN Method, Description & Sample Call


1 init ( self [,args...] )
Constructor (with any optional arguments) Sample Call : obj =
className(args)
2 del ( self )
Destructor, deletes an object
Sample Call : del obj
3 repr ( self )
Evaluatable string representation
Sample Call : repr(obj)
4 str ( self )
Printable string representation
Sample Call : str(obj)
5 cmp ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Overloading Operators

Suppose you have created a Vector class to represent two-dimensional


vectors. What happens when you use the plus operator to add them? Most
likely Python will yell at you.

You could, however, define the add method in your class to perform
vector addition and then the plus operator would behave as per expectation −

Example

A. Irungu
class Vector:
def __init__ (self, a, b):
self.a = a
self.b = b
def __str__ (self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.ar + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
Data Hiding (Private data members)

An object's attributes may or may not be visible outside the class definition.
Then the names of attributes are preceded with a double underscore prefix,
those attributes are not be directly visible to outsiders.

Example

class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count() #private attribute =1
counter.count() #private attribute =2
print (counter.__secretCount) # This line will throw an error
print (counter._JustCounter__secretCount) # This line will work

Python protects those members by internally changing the name to include


the class name. However, Such attributes can be accessed as
object._className__attrName.

A. Irungu
Lesson 9: Exceptions Handling
Python provides two very important features to handle any unexpected
error in a program and to add debugging capabilities-

 Exceptions
 Assertions

StandardExceptions

EXCEPTION DESCRIPTIO
N
Exception Base class for all exceptions
StopIteration Raised when the next() method of
an iterator does not point to any
object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions
except StopIteration
andSystemExit.
ArithmeticError Base class for all errors that occur
for numeric calculation.
OverflowError Raised when a calculation exceeds
maximum limit for a numeric type.
FloatingPointError Raised when a floating point
calculation fails.
ZeroDivisionError Raised when division or modulo by
zero takes place for all numeric
types.
AssertionError Raised in case of failure of the
Assert statement.
AttributeError Raised in case of failure of attribute
reference or assignment.
EOFError Raised when there is no input from either the
raw_input() or input() function and the end of file is
reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the
dictionary.
NameError Raised when an identifier is not found in the local or
global namespace.
UnboundLocalError Raised when trying to access a local variable in a
function or method but no value has been assigned to
it.

A. Irungu
EnvironmentError Base class for all exceptions that occur outside the
Python environment.
IOError Raised when an input/ output operation fails, such as
the print statement or the open() function when trying
to open a file that does not exist.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem,
but when this error is encountered the Python
interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the
sys.exit() function. If not handled in the code, causes
the interpreter to exit.
TypeError Raised when an operation or function is attempted
that is invalid for the specified data type.
ValueError Raised when the built-in function for a data type has
the valid type of arguments, but the arguments have
invalid values specified.
RuntimeError Raised when a generated error does not fall into any
category.
NotImplementedError Raised when an abstract method that needs to be
implemented in an inherited class is not actually
implemented.

Assertions inPython
An assertion is a sanity-check that can be turned on or off when the testing
of a program is completed. An expression is tested, and if the result comes up
false, an exception is raised. Programmers often place assertions at the start
of a function to check for valid input, and after a function call to check for
valid output.
The assert Statement
When an assert statement is encountered, the accompanying expression is
evaluated, with the expectation that the statement is true. If the expression is
false, Python raises an AssertionError exception. If the assertion fails, Python
uses ArgumentExpression as the argument for the AssertionError.
AssertionError exceptions can be caught and handled like any other
exception, using the try-except statement. If they are not handled, they will
terminate the program and produce a traceback.
Example

Here is a function that shares a number of items to a number of beneficiaries. If


a number of beneficiaries exceed the number of items, the function bails out.
def mydiv(items, beneficiaries):
assert (items>beneficiaries),"Items to be shared are less"
return items/beneficiaries
print (mydiv(20,4))

A. Irungu
print (mydiv(4,10)) # the program will crash at this point
print (mydiv(9,4))
print (mydiv(7,0))
print (mydiv(12,3))
What is Exception?

It is an event which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
HandlinganException

In cases where the code may raise an exception, the program can be protected
from crashing by placing the suspicious code in a try: block. After the try:
block, an except: statement is included, followed by a block of code which
handles the problem as elegantly as possible.

When handling Exceptions;

 A single try statement can have multiple except statements. This is


useful when the try block contains statements that may throw different
types of exceptions.
 A generic except clause can be used; in which case it handles any
exception.
 After the except clause(s), an else-clause can be included. The code in
the else- block is executed if the code in the try: block does not raise an
exception.
 The else-block is a good place for code that does not need the try:
block's protection.
Example 1:

def mydiv(items, beneficiaries):


share=0
try:
assert (items>beneficiaries),"Items to be shared are less"
share= items/beneficiaries
except AssertionError:
print ("Items to be shared are less.", end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(20,4))
print ("Share = ", mydiv(4,10))
print ("Share = ", mydiv(9,4))
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))

A. Irungu
Example 2:

def mydiv(items, beneficiaries):


share=0
try:
assert (items>beneficiaries),"Items to be shared are less"
share= items/beneficiaries
except AssertionError:
print ("Items supplied are less.", end='\t')
except ZeroDivisionError:
print ("No Beneficiaries.", end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(20,4))
print ("Share = ", mydiv(4,10))
print ("Share = ", mydiv(9,4))
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))

The except Clausewith NoExceptions

An except statement can be used with no exceptions defined, in which case all
kind if exceptions are caught. This kind of try-except statement is not
considered a good practice, because even though it catches all exceptions, it
does not make the programmer identify the root cause of the problem that may
occur.
Example

def mydiv(items, beneficiaries):


share=0
try:
assert (items>beneficiaries),"Items to be shared are less"
share= items/beneficiaries
except:
print ("Errors Found.", end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(20,4))
print ("Share = ", mydiv(4,10))
print ("Share = ", mydiv(9,4))
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))
The except ClausewithMultiple Exceptions

The same except statement can be used to handle multiple exceptions as


follows-

Example 2:

A. Irungu
def mydiv(items, beneficiaries):
share=0
try:
assert (items>beneficiaries),"Items to be shared are less"
share= items/beneficiaries
except (AssertionError, ZeroDivisionError):
print ("Errors Found. ",end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(20,4))
print ("Share = ", mydiv(4,10))
print ("Share = ", mydiv(9,4))
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))

Argument ofan Exception


An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by
exception.
def mydiv(items, beneficiaries):
share=0
try:
assert (items>beneficiaries),"Items to be shared are less"
share= items/beneficiaries
except AssertionError as argument:
print (argument, end='\t')
except ZeroDivisionError as argument:
print (argument, end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(20,4))
print ("Share = ", mydiv(4,10))
print ("Share = ", mydiv(9,4))
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))

To handle a single exception, the variable follows the name of the exception in
the except statement.
To handle multiple exceptions, you can have a variable follow the tuple of the
exceptions.
except (AssertionError, ZeroDivisionError) as argument:
print (argument, end='\t')

A. Irungu
Raisingan Exception
Exceptions can be raised in several ways, using the raise statement.
Syntax

raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (for example, NameError) and args
is a value for the exception argument, which is optional; if not supplied, the
exception argument is None. The final argument, traceback, is also optional (and
rarely used in practice), and if present, is the traceback object used for the
exception.
In order to catch an exception, an "except" clause must refer to the same
exception thrown either as a class object or a simple string.
Example:

def mydiv(items, beneficiaries):


share=0
try:
if (items<beneficiaries):
raise Exception("Less items to be Shared")
share= items/beneficiaries
except (ZeroDivisionError, Exception) as argument:
print (argument, end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(20,4))
print ("Share = ", mydiv(4,10))
print ("Share = ", mydiv(9,4))
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))

def allocate (budget,projects):


share=0
try:
if (budget>projects):
raise Exception("Budget is Not Enough.")
share=budget/projects
except Exception as x:
print (x,"Share =",end="\t")
share=0;
return share
print (allocate (10,5))
print (allocate (5,20))
print (allocate (0,4))
print (allocate (6,0))
print (allocate (12,5))

A. Irungu
User-Defined Exceptions
Exceptions can be created by deriving classes from the standard built-in
exceptions. i.e. Inheriting from existing exceptions

Here is an example related to RuntimeError. Here, a class is created that is


subclassed from RuntimeError. This is useful when you need to display more
specific information when an exception is caught.

In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.

class SharingError(ZeroDivisionError):
def __init__ (self, arg):
self.args = arg

def mydiv(items, beneficiaries):


share=0
try:
if (beneficiaries==0): raise SharingError(["Div By Zero"])
share= items/beneficiaries
except SharingError as e:
print (e, end='\t')
else:
print ("Shared Successfully.", end='\t')
return share
print ("Share = ", mydiv(7,0))
print ("Share = ", mydiv(12,3))

A. Irungu
Lesson 10: File handling
This chapter covers some of the basic I/O functions available in Python 3.
Printing to the Screen
The simplest way to produce output is using the print statement where you can
pass zero or more expressions separated by commas. This function converts
the expressions you pass into a string and writes the result to standard output
as follows-
print ("Hello World,", " Hello Again")
Reading KeyboardInput
The input() functions read data from keyboard as string, irrespective of
whether it is enclosed with quotes ('' or "" ) or not.
Opening and Closing Files
Python provides basic functions and methods necessary to manipulate files by
default. Most of the file manipulations can be done using a file object.

The open Function

Using Python’s built-in open() function a file can be opened for either reading
or writing. This function creates a file object, which can be utilized to call
other support methods associated with it.
Syntax:

file object = open(file_name [, access_mode][, buffering])

 file_name: The file_name argument is a string value that contains the


name of the file to be accessed.
 access_mode: The access_mode determines the mode in which the file
has to be opened, i.e., read, write, append, etc. A complete list of
possible values is given below in the table. This is an optional parameter
and the default file access mode is read (r).
 buffering: If the buffering value is set to 0, no buffering takes place.
If the buffering value is 1, line buffering is performed while accessing a
file. If you specify the buffering value as an integer greater than 1, then
buffering action is performed with the indicated buffer size. If negative,
the buffer size is the system default (default behavior).
The different modes of opening a file are:

Modes Description

r Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.

A. Irungu
r+ Opens a file for both reading and writing. The file pointer placed at
the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if
the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for
reading and writing.
wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The
file pointer is at the end of the file if the file exists. The file opens in
the append mode. If the file does not exist, it creates a new file for
reading and writing.

The file Object Attributes

Once a file is opened and you have one file object, you can get various
information related to that file.
The attributes related to a file object are:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.

The close() Method

The close() method of a file object flushes any unwritten information and
closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.
Example

myfile = open("test.txt", " w+")

A. Irungu
print ("Name of the file: ", myfile.name)
print ("Closed or not : ", myfile.closed)
print ("Opening mode : ", myfile.mode)
myfile.close()

Readingand Writing Files


The file object provides a set of access methods to make our lives easier. We
would see how to use read() and write() methods to read and write files.

The write() Method

The write() method writes any string (, passed parameter) to an open file. It is
important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the
string-

Example

myfile = open("test.txt", "w")


myfile.write( "First line.\nSecond Line\n")
myfile.close()

The read() Method

This methos takes a parameter, being the number of bytes to be read from the
opened file. This method starts reading from the beginning of the file and if the
parameter is missing, then it tries to read as much as possible, maybe until the
end of file.
Example

myfile = open("test.txt", "r")


print (myfile.read())
myfile.close()

File Positions

The tell() method retruns the current position within the file; ie. the next read
or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset
argument indicates the number of bytes to be moved. The from argument
specifies the reference position from where the bytes are to be moved.
If from is set to 0, the beginning of the file is used as the reference position. If it
is set to 1, the current position is used as the reference position. If it is set to 2
then the end of the file would be taken as the reference position.

Example

myfile = open("test.txt", "r+") # Open a file

A. Irungu
rstr = myfile.read(5)
print ("Reading up to position 5: \n", rstr)
position = myfile.tell() # Check current position
print ("Current file position : ", position)
myfile.seek(15, 0) # Moving the pointer ahead
rstr = myfile.read(6)
print ("Reading six positions from here : ", rstr) # Close opened file
myfile.close()

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files. The module needs to be
imported first, before any of its related functions is called.
Ie. import os
rename() Method os.rename(current_file_name, new_file_name)
remove() Method os.remove(file_name)

Directories in Python
The os module has several methods that help you create, remove, and
change directories.
mkdir() You can use the mkdir() method of the os os.mkdir("newdir")
module to create directories in the current
directory.
chdir() You can use the chdir() method to change os.chdir("newdir")
the current directory.
getcwd() The getcwd() method displays the current os.getcwd()
working directory.
rmdir() The rmdir() method deletes the directory, os.rmdir('dirname')
which is passed as an argument in the
method. Before removing a directory, all the
contents in it should be removed.

File &DirectoryRelated Methods

There are three important sources, which provide a wide range of utility methods
to handle and manipulate files & directories on Windows and Unix operating
systems. They are as follows-

File Object Methods: The file object provides functions to manipulate files.

OS Object Methods: This provides methods to process files as well as


directories.

A. Irungu
File Methods

A file object is created using open function and here is a list of functions
which can be called on this object.

S. No. Methods with Description


1 file.close()Close the file. A closed file cannot be read or written any
more.
2 file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on
some file-like objects.
3 file.fileno()Returns the integer file descriptor that is used by the
underlying implementation to request I/O operations from the
operating system.
4 file.isatty()Returns True if the file is connected to a tty(-like) device,
else False.
5 next(file)Returns the next line from the file each time it is being
called.
6 file.read([size])Reads at most size bytes from the file (less if the
read hits EOF before obtaining size bytes).
7 file.readline([size])Reads one entire line from the file. A trailing
newline character is kept in the string.
8 file.readlines([sizehint])Reads until EOF using readline() and return
a list containing the lines. If the optional sizehint argument is present,
instead of reading up to EOF, whole lines totalling approximately
sizehint bytes (possibly after rounding up to an internal buffer size)
are read.
9 file.seek(offset[, whence])Sets the file's current position
10 file.tell()Returns the file's current position
11 file.truncate([size])Truncates the file's size. If the optional size
argument is present, the file is truncated to (at most) that size.
12 file.write(str)
Writes a string to the file. There is no return value.
13 file.writelines(sequence)Writes a sequence of strings to the file. The
sequence can be any iterable object producing strings, typically a list of
strings.

OS File/Directory Methods

The os module provides a big range of useful methods to manipulate files and
directories. Most of the useful methods are listed here:
S. Methods with Description
No.
1 os.access(path, mode)Use the real uid/gid to test for access to path.
2 os.chdir(path)Change the current working directory to path
3 os.chflags(path, flags)Set the flags of path to the numeric flags.
4 os.chmod(path, mode)Change the mode of path to the numeric
mode.

A. Irungu
5 os.chown(path, uid, gid)Change the owner and group id of path to
the numeric uid and gid.
6 os.chroot(path)Change the root directory of the current process to
path.
7 os.close(fd)Close file descriptor fd.
8 os.closerange(fd_low, fd_high)Close all file descriptors from fd_low
(inclusive) to fd_high (exclusive), ignoring errors.
9 os.dup(fd)Return a duplicate of file descriptor fd.
10 os.dup2(fd, fd2)Duplicate file descriptor fd to fd2, closing the latter
first if necessary.
11 os.fchdir(fd) Change the current working directory to the directory
represented by the file descriptor fd.

12 os.fchmod(fd, mode)Change the mode of the file given by fd to the


numeric mode.
13 os.fchown(fd, uid, gid)Change the owner and group id of the file
given by fd to the numeric uid and gid.
14 os.fdatasync(fd)Force write of file with filedescriptor fd to disk.
15 os.fdopen(fd[, mode[, bufsize]])Return an open file object
connected to the file descriptor fd.
16 os.fpathconf(fd, name)Return system configuration information
relevant to an open file. name specifies the configuration value to
retrieve.
17 os.fstat(fd)Return status for file descriptor fd, like stat().
18 os.fstatvfs(fd)Return information about the filesystem containing the
file associated with file descriptor fd, like statvfs().
19 os.fsync(fd)Force write of file with filedescriptor fd to disk.
20 os.ftruncate(fd, length)
Truncate the file corresponding to file descriptor fd, so that it is at
most length bytes in size.
21 os.getcwd()Return a string representing the current working
directory.
22 os.getcwdu()Return a Unicode object representing the current
working directory.
23 os.isatty(fd)Return True if the file descriptor fd is open and connected
to a tty(-like) device, else False.
24 os.lchflags(path, flags)Set the flags of path to the numeric flags,
like chflags(), but do not follow symbolic links.
25 os.lchmod(path, mode)Change the mode of path to the numeric
mode.
26 os.lchown(path, uid, gid)Change the owner and group id of path to
the numeric uid and gid. This function will not follow symbolic links.
27 os.link(src, dst)Create a hard link pointing to src named dst.
28 os.listdir(path)Return a list containing the names of the entries in the
directory given by path.
29 os.lseek(fd, pos, how)
Set the current position of file descriptor fd to position pos, modified
by how.
30 os.lstat(path)Like stat(), but do not follow symbolic links.
31 os.major(device)Extract the device major number from a raw device
6

A. Irungu
number.
32 os.makedev(major, minor)Compose a raw device number from the
major and minor device numbers.
33 os.makedirs(path[, mode])Recursive directory creation function.
34 os.minor(device)Extract the device minor number from a raw device
number .
35 os.mkdir(path[, mode])Create a directory named path with numeric
mode mode.
36 os.mkfifo(path[, mode])Create a FIFO (a named pipe) named
path with numeric mode mode. The default mode is 0666 (octal).
37 os.mknod(filename[, mode=0600, device])Create a filesystem
node (file, device special file or named pipe) named filename.
38 os.open(file, flags[, mode])
Open the file file and set various flags according to flags and possibly
its mode according to mode.
39 os.openpty()Open a new pseudo-terminal pair. Return a pair of file
descriptors (master, slave) for the pty and the tty, respectively.
40 os.pathconf(path, name)Return system configuration information
relevant to a named file.
41 os.pipe()Create a pipe. Return a pair of file descriptors (r, w)
usable for reading and writing, respectively.
42 os.popen(command[, mode[, bufsize]])Open a pipe to or from
command.
43 os.read(fd, n)Read at most n bytes from file descriptor fd. Return a
string containing the bytes read. If the end of the file referred to by fd
has been reached, an empty string is returned.
44 os.readlink(path)Return a string representing the path to which the
symbolic link points.
45 os.remove(path)Remove the file path.
46 os.removedirs(path)Remove directories recursively.
47 os.rename(src, dst)Rename the file or directory src to dst.
48 os.renames(old, new)Recursive directory or file renaming function.
49 os.rmdir(path)Remove the directory path
50 os.stat(path)Perform a stat system call on the given path.
51 os.stat_float_times([newvalue])Determine whether stat_result
represents time stamps as float objects.
52 os.statvfs(path)Perform a statvfs system call on the given path.
53 os.symlink(src, dst)Create a symbolic link pointing to src named dst.
54 os.tcgetpgrp(fd)Return the process group associated with the
terminal given by fd (an open file descriptor as returned by open()).
55 os.tcsetpgrp(fd, pg)Set the process group associated with the
terminal given by fd (an open file descriptor as returned by open()) to
pg.
56 os.tempnam([dir[, prefix]])
Return a unique path name that is reasonable for creating a temporary
file.
57 os.tmpfile()Return a new file object opened in update mode (w+b).
58 os.tmpnam()Return a unique path name that is reasonable for
creating a temporary file.
59 os.ttyname(fd)Return a string which specifies the terminal device
7

A. Irungu
associated with file descriptor fd. If fd is not associated with a
terminal device, an exception is raised.
60 os.unlink(path)Remove the file path.
61 os.utime(path, times)Set the access and modified times of the file
specified by path.
62 os.walk(top[, topdown=True[, onerror=None[,
followlinks=False]]])Generate the file names in a directory tree by
walking the tree either top-down or bottom-up.
63 os.write(fd, str)Write the string str to file descriptor fd. Return the
number of bytes actually written.

def countspaces(file):
fx= open(file)
count=0
text=fx.read()
for w in text:
if (w==" "): count+=1
fx.close()
return count
print(countspaces("test3.txt"))

A. Irungu
Lab Exercises: Using Strings, Lists, Tuples, and
Dictionary

A. Irungu
References
Tutorialspoint. (2016). Python 3 Tutorial. Tutorialspoint.

10

A. Irungu

You might also like