CCS3255 CourseNotes
CCS3255 CourseNotes
Course Content:
Mode of Delivery
Course Assessment
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 3: Operators
Lesson 5: Loops
Lesson 6: Functions
Lesson 7: Modules
A. Irungu
Table of Contents
Lesson 1: Introduction ................................................................1
Identifiers ........................................................................................... 3
Quotations .......................................................................................... 3
Comments ........................................................................................... 4
Statements.......................................................................................... 4
if statement ......................................................................................... 1
A. Irungu
Loop Control Statements ....................................................................... 3
Assignment: ........................................................................................ 5
Creating Classes..................................................................................... 1
ii
A. Irungu
Overriding Methods .................................................................................. 6
Raising an Exception.................................................................................. 6
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.
Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
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-
Installing Python
Discuss in groups and find out the best way / form of python installation
Starting 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.
While on Linux /Unix platforms always ensure the file permission mode allows
execution.
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.
• 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.
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
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:
Strings
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example-
A. Irungu
Library")
Homework:
Lists
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-
Homework:
Tuples
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-
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:
Dictionary
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example-
Homework:
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.
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.
Example
Homework:
A. Irungu
Lesson 3: Operators in Python
Operators are the constructs, which can manipulate the value of operands
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
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
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
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
Identity Operators
Operator precedence
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-
if statements
if...else statements,
nested if statements
if statement
Example 1
age = 20
if age:
print ("Age is true")
print (age)
Example 2
A. Irungu
if... else statements
Syntax
if expression:
statement(s)
else:
statement(s)
Example
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
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
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.
a) while loop
b) for loop
c) nested loops .
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
Example 1
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.
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.
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.
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.
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.
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.
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:
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.
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
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
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
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
Example:
Variable-length Arguments
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
Example
Return Statement
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.
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-
Example
import calendar
print (calendar.calendar(2022))
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")
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:
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.
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__. ".
A. Irungu
When you run the above code, the following output will be displayed.
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:
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.
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 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
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
import mypack as m
m.factorial(6);
m.hello()
m.loop()
Assignment:
Read and Discuss the following ecosystem among your study groups;
Modules
Packages
Libraries
Frameworks
A. Irungu
Lesson 8: Object-Oriented Programming in Python
Creating Classes
The class statement creates a new class definition.
Syntax:
class ClassName:
'Optional class documentation string'
class_suite
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:
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.
Example:
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.
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.
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
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 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
A. Irungu
Overriding Methods
Overriding of parent methods is done when a different functionality in desired
in the derived class.
Example
Overloading Operators
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
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
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.
A. Irungu
Example 2:
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
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))
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
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:
A. Irungu
User-Defined Exceptions
Exceptions can be created by deriving classes from the standard built-in
exceptions. i.e. Inheriting from existing exceptions
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
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.
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:
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.
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 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
A. Irungu
print ("Name of the file: ", myfile.name)
print ("Closed or not : ", myfile.closed)
print ("Opening mode : ", myfile.mode)
myfile.close()
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
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
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
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()
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.
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.
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.
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.
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