CSC 201 Lecture Slides

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 201

Comparative Programming (CSC 202)

Department of Computer Science

FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE (FUTA)


Comparative Programming (CSC 202)

LECTURE 1
I n t r o d u c ti o n t o P y t h o n P r o g r a m m i n g
Introduction: What is Python?

Developed by Guido van Rossum in the Netherlands in the late ‘80s .


Python 2.0 was released on 16 October 2000. However, even though Python 3 has
been released since 3rd of December 2008, Python 2.7 still remains the most stable
version and will be used throughout this class.
It is an open-source, general-purpose, and high level programming language with
remarkable power.
Simple, clean, readable and yet compact syntax.
Easy to learn and very well suitable for learning to program.
Due to its large user community, Python is experience continuous development .
Highly compatible with many leading programming languages and frameworks
such as Java, C/C++, C#.NET etc.
See www.python.org for more information on the Python language.
Introduction: features of Python
Python possesses many interesting technical and aesthetic features.
Support multiple programming paradigms e.g. structured, object-oriented, and
functional programming
Open Source
Interactive: provides interactive command line interface for instantaneous scripting
Easily extensible: third-party codes/library can easily be integrated
Interpreted language
Dynamic language: supports dynamic typing of variables, and objects and doesn’t
require static declaration of variables to be of particular types.
Platform independent i.e. Python can run on Windows, Apple Mac, Solaris, Linux etc.
Large library of codes: many special purpose third-party libraries are available
Support varieties of data structures and built-in types e.g. tupples, list, dictionaries,
decorators, iterators etc.
Large user support community
Introduction: Development Tools

Text Editor
o Notepad, Notepad++, Sublime Text 2, EditPad etc

Integrated Development Environment


o Python IDLE, Eclipse, EditPadPro, GEdit, JEdit, Komodo IDE,
Netbeans, PythonToolKit etc.

Python Interpreter
www.python.org/download/
Introduction: Python Basics
Case/Space Sensitivity
- python codes are highly case sensitive so print is not equivalent to
PRINT or Print
- the use of whitespaces is revered and so must be used
appropriately. Indentation is important! You must indent properly or
your code will not work!
Variable Naming
- Python names can be as long as 255 characters, starts with a letter
or _ followed by a mix of alpha-numerics and the underscore. Python
keywords are not allowed to be used as variable names.
Data Types
- even though it’s strictly dynamic and does not Value Type
require static variable declarations, the 203 int
following basic types are supported. 4.03 float
- however complex types such as arrays, list,
“futa!" str
tupple, sets, dictionaries and user defined
types are also supported.
Python: Variables
Variables in python are dynamic i.e. they do not need to be declared as python
automatically infers the type based on the type of data stored them and how they
are used in expressions. 1 >>> score = 60
- Python assigns memory to a 2 >>> matno = “CSC/11/0036”
3 >>> height = 4.5
variable only when the variable is 4 >>> isGraduated = False
initialized. >>> score
60

- Python also supports scientific


1 >>> comp = 4 + 3j
types such as Complex Numbers 2 >>> print comp
and also provides means to carry 3 (4+3j)
out basic operations on them. 4 >>> comp.real
5 4.0j
E.g. Getting the real, imaginary 6 >>> comp.imag
part or the conjugate of the 7 3.0
complex number. 8 >>> comp.conjugate()
9 (4-3j)
Python: Expressions & Operators
Python supports the following basic arithmetic operators;
Operators Operation Precedence 1 >>> 23+6*3-9/6*2**3
2 33
+ Addition () 3 >>> 5 % 3
- Subtraction ** 4 2
5 >>> 10 / 3
* Multiplication */% 6 3
/ Division +- 7 >>> 10.0 / 3
8 3.3333333333333335
% Modulo 9 >>> 10 // 3
** Exponentiatio 10 3
n 11 >>> 10.0 // 3
12 3.0
// Floor Division 13 >>> 3 ** 2 ** 3
14 6561
15 >>> a = 2 + 3j
Pay attention to the disparity in the 16 >>> b = 3 + 6j
use of / and // 17 >>> c = a + b
18 >>> c
19 (5+9j)
Python: Expressions & Operators
Python supports the following basic relational operators;
All relational operators produce only boolean result!

Operators Operation 1 >>> a = 30


2 >>> b = 32
< Less Than 3 >>> a < b
> Greater Than 4 True
5 >>> a > b
== Equal To 6 False
<= Less Than or 7 >>> a >= b
Equal To 8 False
9 >>> b <= a
>= Greater Than 10 False
or Equal To 11 >>> a != b
12 True
!= Not Equal To 13 >>> a == 30
14 True
Python: Expressions & Operators
Python supports the following basic logic operators;
They are usually used to combine multiple groups of relational expressions and
produce only boolean result!
Operators Operation
and CONJUNCTION
or DISJUNCTION

not NEGATION

1 >>> (a<b) and (a>b)


2 False
3 >>> (b<=a) or (a != b)
4 True
5 >>> not(a == 30)
6 False
7 >>> (a<b) and (a>b) and (not((b<=a) or (a != b)))
8 False
Python: Type Conversion
We can use the type() to know the type of a variable.
1 >>> type(3+4j)
2 <type 'complex'>
3 >>> x = 3
4 >>> type(x)
5 <type 'int'>
6 >>> name = "FUTA"
7 >>> type(name)
8 <type 'str'>

Python provides functions int(), float(), str() to convert between types appropriately
1 >>> a = 30.5
2 >>> b = 3
3 >>> a/b
4 10.166666666666666
5 >>> int(a/b)
6 10
7 >>> float(b)
8 3.0
9 >>> age = "25"
10 >>> age_int = int(age)
11 >>> str(age_int)
12 '25'
Python: Comments
The # character is used to comment a line of code in python. Therefore anything after a #
is ignored by the python compiler
Comments can be used
 to describe what is going to happen in a program or
 Document information about a program such as the author and date or place
 Can also be used to turn off a portion of codes temporarily or permanently

1 # Author: Muyi Ibidun


2 # Date: 17/03/2013
3 # Remark: Program to compute the average of 3 numbers
4
5 # This portion assigns values to the variables
6 x = 300
7 y = 456.78
8 z = 2345
9
10 w = x + y + z # this line computes the sum
11
12 # compute average and display average
13 m = w / 3
14 print m
Comparative Programming (CSC 202)

LECTURE 2
P y t h o n I / O & C o m m a n d - L i n e I n t e r a c ti o n
Python I/O and Command-line Interaction

Python can be used in two modes;


 The Interactive Mode:
- This mode allows users to type commands into a shell prompt
(DOS- like interface)

- In this mode it prompts for the next command with the primary prompt, usually
three greater-than signs (>>>); for continuation lines it prompts with the
secondary prompt, by default three dots (...). The interpreter prints a welcome message
stating its version number and a copyright notice before printing the first prompt:
Python I/O and Command-line Interaction

 The Code/Normal Mode:


- While the interactive mode is appropriate for short scripting tasks or coding. The
code mode provides an environment for writing long and complete programs. The
code mode provide code highlighting, intellisense and auto-suggestion features.
Python I/O and Command-line Interaction
The interactive mode can be used as a calculator, as a tool for testing lines of codes,
or for writing simple system administration scripting.
For example see below;

1 >>> b = 10 * 5
2 >>> x = 400 + b
3 >>> print b
4 50
5 >>> print x
6 450
7 >>> print a,b
8 50, 450
9 >>> dir()
10 [‘__builtins__’,’ __docs__’,’ __name__’,’b’,’x’]

When the interactive is started, it keeps a collection of all variables and objects initialized
or created during a particular code session and persists such until the shell is exited or
restarted . Line:9 shows how to view a list of the active list of objects.
Python I/O and Command-line Interaction
Displaying code output
Using Print : the print keyword can be used to display program
output as shown in the figure below;
Notice how function 1 >>> name = "Wole"
2 >>> age = 56
str() on line:12 is used to 3 >>> print name
convert the integer 4 Wole
5 >>> print name,age
variable age to a string. 6 Wole 56
7 >>> print name;age
8 Wole
9 56
10 >>> print "Name: "+ name
11 Name: Wole
12 >>> print "Age: "+ str(age)
13 Age: 56
Python I/O and Command-line Interaction
Reading data input from the keyboard
raw_input: the raw_input() function can be used to read in
users’ inputs as shown in the figure below;
1 >>> matric = raw_input("What is your matric number?")
2 What is your matric number?CSC/05/6442
3 >>> print matric
4 CSC/05/6442
5 >>> score_test = raw_input("What is your test score?")
6 What is your test score?20
7 >>> score_exam = raw_input("What is your exam score?")
8 What is your exam score?56
9 >>> total_score_CSC201 = int(score_test) + int(score_exam)
10 >>> print total_score_CSC201
11 76

raw_input() function takes a single parameter that represents the prompt


message guiding users on what to input as shown above.
raw_input() functions return primarily string values and must be
converted to appropriate types using either int() or float() functions as
shown above or even str() as the case maybe.
Python I/O and Command-line Interaction
Using help() on the command line interface
help(): it is used to learn more about the python language. It
displays the documentation of many common topics in python.
1 >>> help()
2 Welcome to Python 2.7! This is the online help utility.
3 If this is your first time using Python, you should
definitely check out the tutorial on the Internet at
http://docs.python.org/tutorial/.
4 Enter the name of any module, keyword, or topic to get help
on writing Python programs and using Python modules. To quit
this help utility and return to the interpreter, just type
"quit".
5 To get a list of available modules, keywords, or topics, type
"modules", "keywords", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules
whose summaries contain a given word such as "spam", type
"modules spam".
help>
Python I/O and Command-line Interaction
Using help() on the command line interface
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')” has the
same effect as typing a particular string at the help> prompt.
1 >>> help("if")
2 The ``if`` statement
3 ********************

4 The ``if`` statement is used for conditional execution:

5 if_stmt ::= "if" expression ":" suite


( "elif" expression ":" suite )*
["else" ":" suite]

6 It selects exactly one of the suites by evaluating the expressions one


by one until one is found to be true (see section *Boolean operations*
for the definition of true and false); then that suite is executed
(and no other part of the ``if`` statement is executed or evaluated).
7 If all expressions are false, the suite of the ``else`` clause, if
present, is executed.

8 Related help topics: TRUTHVALUE


Python I/O and Command-line Interaction
Using help() on the command line interface
1 >>> age = 30
2 >>> isOld = (age > 30)
3 >>> help(isOld)
Help on bool object:

class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
| Methods defined here:
| __and__(...)
| x.__and__(y) <==> x&y
| __or__(...)
| x.__or__(y) <==> x|y
|…… …… …… ……
| Methods inherited from int:
| __abs__(...)
| x.__abs__() <==> abs(x)
| __add__(...)
| x.__add__(y) <==> x+y
| …… …… …… …..
Python I/O and Command-line Interaction
Using dir() on the command line interface
 typing dir() returns the names in the current scope of the interpreter,
while typing dir(object) returns a list of strings containing the object’s
attributes, and class's attributes etc.
1 >>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'age',
'isOld', 's‘]

2 >>> dir(age)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
'__floordiv__', '__format__', '__getattribute__', '__getnewargs__',
'__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__',
'__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__',
'__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__',
'__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__',
'__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',
'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
Comparative Programming (CSC 202)

LECTURE 3
Python Control Structures
Control Structures
 Normally, statements in a program (including the ones we have
written so far) are executed sequential order.
 Various Python statements enable the programmer to specify the
order in which programs are to be executed. This is called transfer of
control.
 Transfer of control is achieved with Python control structures. This
lecture discusses the control structures available in Python.

- Python provides two major categories of control structures:


 Selection Structures
 Repetition Structures
Control Structures: Selection
Selection Structures:
The selection structures enable Python to make decision, selecting one
of two or more possible paths depending on the outcome of an already
tested condition(s).

The available selection structures in Python are

if,
If…else and
If…elif….else.
Control Structures: Selection
The if Statement:
It enables Python to choose among alternative courses of action. It
either performs (selects) an action if a condition (predicate) is true or
skips the action if the condition is false. It is a single-selection structure
because it selects or ignores a single path of action.
Syntax: The general form of an if-structure is:
if (expression):
<python statements>
<python statements>
…. ….. ….. …..
where expression is either true or false. If the expression is true,
Python executes the list of statements under the if block; if not, it
doesn't do anything.
Control Structures: Selection

Example 3.1:
The figure below is a schematic of how the if statement works. In
this case, the if block prints “Passed” only when the value of variable
Grade is greater or equal to 60.

1 >>> Grade = 87
2 >>> if(Grade >= 60):
3 print "Passed“
4
5 Passed
Control Structures: Selection

Example 3.2:
Write a Python program to test whether 10 is greater than 5
1 >>> if (10 > 5):
2 print("10 is greater than 5")
3
4 10 is greater than 5

1 >>> age = int(raw_input("What is


Example 3.3: 2 your age?"))
3 What is your age?21
Write a Python program to 4 >>> if age > 18 :
determine if a student is 5 print "You are an adult!"
an adult 6
7
8 You are an adult!
9 >>>
Control Structures: Selection
The if…else Statement:
The if-else selection structure allows the programmer to specify that a
different action is to be performed when a condition is true from an
action when a condition is false.

Syntax:
The general form of an if/else structure is:
if (expression):
<python statements1>
else:
<python statements2>

where expression is either true or false. If the expression is true,


Python executes the <python statements1>; if not, it execute <python
statements1>
Control Structures: Selection

Example: Write a Python program to print “Pass” if a student’s is


greater than or equal to 40 but print “Fail” if otherwise.
1 Grade = 60
2 if (Grade >= 40):
3 print("Pass !")
4 else:
5 print("Fail !")
6
7 >>>
8 Pass !
Control Structures: Selection
The if…..elif……else Statement:
This allows for a case when we have multiple conditions and
corresponding actions to perform

Syntax: The general form of an if..elif..else structure is:


if (expression 1):
<python statements1>
elif(expression 2):
<python statements2>
else:
<python statements3>
where expression is either true or false. This is translated by Python as
"If the expression is true, execute the corresponding suite; else, if the
next expression is true, execute the corresponding suite," and so on.
The else clause here is actually optional.
Control Structures: Selection
Control Structures: Selection

Example:
Write a Python program to letter grade; print A for grade >= 70, B for
grade >=60, C for grade >= 50, D for grade >= 40, F for grade < 40.

1 Grade = 60
2 if (Grade >= 70):
3 print("A")
4 elif (Grade >= 60):
5 print("B")
6 elif (Grade >= 50):
7 print("C")
8 elif (Grade >= 40):
9 print("D")
10 else:
11 print("F")
12 >>>
13 B
Control Structures: Repetition
Repetition Structures:
A repetition structure allows the programmer to specify that a program
should repeat an action while some condition remains true. Two
repetition structures available in Python are:

Examples of repetition structures are:

while
for
Control Structures: Repetition
The while Statement:
The while statement executes a suite until a condition is met. The
expression or condition should evaluate to false at some point,
otherwise infinite loop occurs and the program hangs.

Syntax:
The general form of a while statement is:
while (expression):
<python statements1>
else:
<python statements2>

Note: The else clause is optional.


Control Structures: Repetition
Control Structures: Selection
Example: Write a Python program to find the sum of integers
between 1 and 10 and print their sum.
1 sum = 0
2 num = 0
3 while (num < 10):
4 sum = sum + num
5 print(num)
6 num = num + 1
7
8 print 'Sum = ', sum
9 >>>
10 0
11 1
12 2
13 3
14 4
15 5
16 …
17 9
Control Structures: Repetition
The for Statement
Sometimes it is desire that a set of instructions is to executed
repeatedly, the Python for statement allow us to iterate through a
sequence of values.

Syntax:
The general form of a while statement is:

for <var> in <sequence>:


<body: python statements>
<body: python statements >

Where the loop control variable var takes on each successive value in
the <sequence> and the statements in the body of the loop are
executed once for each value of var.
Control Structures: Repetition
The range() function
The function range() is used to create a consecutive sequence of values:
It produces a list of numbers starting with 0 and continuing up to, but
not including a specified maximum value.

The different mode of operation is shown below;


range ( n)
Generates values starting from 0 up to n (but not including n)
range ( start, n)
Generates values starting from start up to n but not including n
range ( start, n, step )
Generates values from start up to n (not including n) intervals step.
Note that when start < n, step is +ve, and when start > n, step is –
ve!
Control Structures: Repetition

Examples
1 >>> range(10)
2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 >>> range(1, 10)
4 [1, 2, 3, 4, 5, 6, 7, 8, 9]
5 >>> range(10, -1)
6 []
7 >>> range(1, 10, 2)
8 [1, 3, 5, 7, 9]
9 >>> range(10, 0,-1)
10 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
11 >>> range(100,130,2)
12 [100, 102, 104, 106, 108, 110, 112, 114, 116, 118,
13 120, 122, 124, 126, 128]
14 >>> range(100,130,5)
15 [100, 105, 110, 115, 120, 125]
16 >>> range(130,100,-5)
17 [130, 125, 120, 115, 110, 105]
Control Structures: Repetition

Examples :
Lets us look at how the range() function is use within a for block ;

1 >>> for k in range(1,6):


2 print k
3
4 1
5 2
6 3
7 4
8 5
9 >>>
Control Structures: Repetition

We can also have complex and nested for loops


Example:
The code below find the product between consecutive even and
odd numbers between 1 and 5 inclusive.
1 >>> for i in range(2,5,2):
2 for j in range(1,6,2):
3 print "%d * %d = %d" % (i,j, (i*j))
4
5 2 * 1 = 2
6 2 * 3 = 6
7 2 * 5 = 10
8 4 * 1 = 4
9 4 * 3 = 12
10 4 * 5 = 20

Note the technique used in line 3, python replaces the first, second and
third %d in format string with the values of i, j and i*j respectively.
Control Structures: Changing Control

Python provides statements for changing the control of repetitive


statements.
Breaking out of a loop:
The break statement is used to stop an iterating loop. The loop is
exited and no more loop code is executed.

Practically, we often want to repeat a set of python lines for a number


of time but there exist a need to stop the loop when a particular
event occurs.

For instance we may want to evaluate a mathematical function say at


a threshold of 0.001!
Control Structures: Changing Control
Example:
Let us approximate equation y below to 1 where x = 1,2,….∞

1 >>> x = 2
2 >>> y =0
3 >>> while(x>0):
4 y = y + (1.0/(x**3))**0.5
5 print "When x = %d, y = %f" % (x,y)
6 x = x + 1
7 if y >= 1:
8 break
Control Structures: Changing Control

See the result is..

1 When x = 2, y = 0.353553
2 When x = 3, y = 0.546003
3 When x = 4, y = 0.671003
4 When x = 5, y = 0.760446
5 When x = 6, y = 0.828488
6 When x = 7, y = 0.882483
7 When x = 8, y = 0.926677
8 When x = 9, y = 0.963714
9 When x = 10, y = 0.995336
10 When x = 11, y = 1.022747
Comparative Programming (CSC 202)

LECTURE 4
D e fi n i n g P y t h o n F u n c ti o n s &
Procedures
Python Functions and Procedures
In general programming, procedures are small, dependent chunks of
codes that can be used to perform some given tasks. The obvious
advantages of using procedures include
Reusability and elimination of redundancy
Modularity and enhanced procedural decomposition
Maintenability
Easy of integration
Readability
There are two types of procedures;
Functions
- python functions are procedures that contain some body of codes to
perform a particular task and return a value.
Subroutines
- These are more or less functions that perform a or some set of task
(s) but do not return a value to the calling program. They are also
called void functions
Python Functions and Procedures
The general structure of a python procedure is shown below;

1 def function_name(list of parameters):


2 statement 1
3 statement 2
4 … … … … … …
5 statement N

Note: python procedures are generally referred to as functions regardless whether


they return or not a value.

Take note of the full colon (:) at the end of line 1, it is used to instruct the
compiler that the next set of instructions are to be taken as a block of codes.
Also important is the indentation as shown in lines 2 to 5. The indentation is
a way of telling the compiler that these statements are under the current
block, function, or even loop.
Python Functions and Procedures

For example: function name


function name
definition keyword parameter
definition keyword

def greet(name) :
def greet() : print “How are you? ”+name
print “How are you?”
function body
function body
use of parameter
It is then easy to call the functions above as follows:
>>> greet() argument
How are you?
>>> greet(“Uche”)
How are you? Uche
Python Functions and Procedures
Python provides some out-of-the-box functions for performing some
common programming tasks called built-in functions.

As well, python allows programmers to define their own custom


functions. These are called user-defined functions.

Some common functions are :


 type conversion functions: int(), float(), str(), type(), bool()

Others include:
len(), chr(), min(), max(), range(), hex(), bin(), abs(), ord(), pow(),
raw_input(), sum(), format(), cmp(), dir(), oct(), round(), print()…etc.

Now lets see the operation of some of these functions….


Python Functions and Procedures

1 >>> len("Technology") 1 >>> min(3,2,5,6,3,-2,4,2,0)


2 10 2 -2
3 >>> chr(65) 3 >>> max(3,2,5,6,3,-2,4,2,0)
4 'A' 4 6
5 >>> ord('B') 5 >>> hex(30)
6 66 6 '0x1e'
7 >>> range(1,10) 7 >>> bin(30)
8 [1, 2, 3, 4, 5, 6, 7, 8, 8 '0b11110'
9 9] 9 >>> oct(30)
10 >>> range (1,20, 3) 10 '036‘
11 [1, 4, 7, 10, 13, 16, 19] 11 >>> cmp(40,32)
12 >>> range (20,1,-5) 12 1
13 [20, 15, 10, 5] 13 >>> cmp(56,89)
14 >>> sum([3,2],0) 14 -1
15 5 15 >>> cmp(2,2)
16 >>> sum(range(1,5), 0) 16 0
17 10 17 >>> pow(3,2)
18 >>> round(0.89377,3) 18 9
19 0.894
Python Functions and Procedures
User-defined void functions or subroutines
- perform a task or set of tasks
- no return a value
- has a function name and may have zero or more parameters
1 def print1to10():
2 for i in range(1,11):
3 print i,
4
5 # to call the function
6 print1to10()
7
>>>
8 1 2 3 4 5 6 7 8 9 10
9
Python Functions and Procedures
 user-defined functions
- perform a task or set of tasks
- it must return a value
- has a function name and may have zero or more parameters
1 def add(a, b):
2 return (a + b)
3
4 x = 3
5 y = 5
6 z = add(x, y)
7 print “{0:d} + {1:d} = {2:d}".format(x, y, z)

8 >>>
9 3 + 5 = 8
Python Functions and Procedures
Scoping
All python objects, variable, or procedures are exists in either of two scopes;
local or global.
Arguments or variables declared in a function are all local to that function
except otherwise designated as global.
The life of a local variable is limited to the confines of the function or module it
is in.
However variables or objects declared outside all functions in a program are
global to all procedures in the program.
1 X = 100
2 def increment(inc):
As in the code sample X is global 3 val = (X + inc)
4 return val
while inc and val are all local to 5 print increment(50)
function increment . 6
7 >>>
8 150
Python Functions and Procedures
Scoping
Python provides for explicit declaration of objects or variables as globals in any
procedure of a module or program.
To declare that the content of variable age is accessible to all functions and
procedures, we declare it as global i.e. we say “global age”
1 >>> version = 1.0
2 >>> print "current version is "+ str(version)
3 current version is 1.0
4 >>> def load_newest_app():
5 global version
6 version = 2.72
7 #........
8 #........
9 print "version in 'load_newest_app = ' "+
10 str(version)
11 >>> load_newest_app()
12 version in 'load_newest_app = ' 2.72
13 >>> print "current version is still "+ str(version)
current version is still 2.72
Comparative Programming (CSC 202)

LECTURE 5
S t r i n g s , S t r i n g s a n d P a tt e r n M a t c h i n g
Processing String Data
Often times in problem solving we would want to store or process
textual data containing characters of the alphabets, numerals and
special characters. Such data are called Strings.
Strings
These are collection of characters that are used to store and represent
textual information. They can be used to store anything data that will
include letters or symbols such as your name, address, department,
course code etc.
Strings in python just like in many other programming languages are
values placed in between a pair of single or double quotes e.g. ‘Ola’,
“CSC202” etc.
There are many operations that can be performed on strings,
enumeration of string characters, concatenation, sorting, deleting
characters, replacing, pattern matching, reversing etc.
Processing String Data

In the memory, strings in python are actually stored as an ordered


sequence of characters. The figure below shows how the string
“Federal, Akure” will be stored.
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

F E D E R A L , A K U R E
0 1 2 3 4 5 6 7 8 9 10 11 12 13

So it can be seen that characters of a strings are actually stored in


consecutive memory locations in memory where the first character
occupies position or index 0 and the second index 1 and to the last
occupying index (N-1) where N is the length(total number of
characters) of the string. However from the rear, the indices is counted
from -1, -2 ……..to –N!
Notice that even spaces are treated like a normal character.
Processing String Data
String Literals
String literals can be written in two forms either using single or double
quotes.
Single Quote:
Name = ‘FUTA’
Double Quote:
Name = “FUTA”
Whichever you use, be assured python treats them equally and it
allows you to be able to embed one in the other.
1 >>> name = "Wheley's“
2 >>> text = 'The new book is titled "Programming in Python"‘
3 >>> print name
4 Wheley's
5 >>> print text
6 The new book is titled "Programming in Python"
Processing String Data
Python automatically concatenates adjacent string literals together. For
example
>>> address = "CSC Dept. " "PMB 704 " "FUT, Akure"
>>> address
'CSC Dept. PMB 704 FUT, Akure‘

Escape Sequence
These are special characters embedded inside string literals to give
them a special meaning or introduce special characters that cannot be
found on the keyboard into the string.
The \ can be used to escape any given character in order to overall
the default behaviour of the character.
For instance putting another ‘ within a pair of ‘ and ‘ flags an error, to
void the error, we can escape the inner ‘ using the \ as shown below;
>>> place = ‘Senate\’s Underground’
Processing String Data
Escape Sequence
 They can also be used to introduce special characters such as the
following in a body of string.
Escape Meaning
1 >>> text = 'SET\\SEET'
\\ Single slash 2 >>> print text
\’ Single quote 3 SET\SEET
4 >>> text = 'Dean\'s Office‘
\” Double quote 5 >>> print text
\n New line 6 Dean's Office
7 >>> text = "The clerk
\t Tab
said \"Come back
\r Carriage return 8 tomorrow!\" "
9 >>> print text
The clerk said "Come back
tomorrow!"
Processing String Data
Escape Sequence
 They can also be used to introduce special characters such as the
following in a body of string.
1 >>> text = "This is the first line,\n Followed by the
2 second line,\n Here is the last line"
3 >>> print text
4 This is the first line,
5 Followed by the second line,
6 Here is the last line
7 >>> text = "Matric\tTest1\tTest2\tExam\tTotal"
8 >>> print text
9 Matric Test1 Test2 Exam Total
10 >>> text = "Matric\tTest1\tTest2\tExam\tTotal\
n======================================"
>>> print text
11 Matric Test1 Test2 Exam Total
12 =====================================
13
Processing String Data
Escape Sequence
 Escape sequences can be suppressed using python raw strings. You
can create a raw string by preceeding a string literal with the character
‘r’ ;

1 >>> text = r"Matric\tTest1\tTest2\tExam\tTotal"


2 >>> print text
3 Matric\tTest1\tTest2\tExam\tTotal
4

With raw strings python ignores the meaning of any escape sequence
present in a string literals
Processing String Data
Escape Sequence
Triple double quote can be used for multiline block strings instead of putting
many \n in a rather long body of text with all whitespaces left as they were in
the original string..
1 >>> text = """These are collection of characters that are
used to store
and represent textual information.
They can be used to store anything data that will include
letters or
symbols such as your name, address, department, course
code etc."""
2 >>> print text
3 These are collection of characters that are used to store
and represent textual information.
They can be used to store anything data that will include
letters or
symbols such as your name, address, department, course
code etc.
Processing String Data
Basic String Operations
Use function len(string) to find the number of characters in the string
Use operator + to concatenate two or more strings
Use * to perform string repetition
Use function str(var) to convert any basic type to string
1 >>> dept = "Computer Science"
2 >>> print len(dept)
3 16
4 >>> print dept * 5
5 Computer ScienceComputer ScienceComputer
ScienceComputer ScienceComputer Science
6 >>> m = 20
7 >>> str(m)
8 '20'
9 >>> eee = "Electrical & " + "Electronics " +
10 "Engineering"
11 >>> print eee
12 Electrical & Electronics Engineering
Processing String Data
Basic String Operations

String Iteration: using loops to enumerate the characters of a string one


after the other.
1 >>> dept = “Computer Science”
2 >>> for char in dept:
3 print char+'\t',
4
5 C o m p u t e r
6 S c i e n c e

We can also check if a string contains another string or a character.

1 >>> "sci" in dept


2 False
3 >>> "put" in dept
4 True
Processing String Data
String Indexing
Because strings are stored in ordered sequence of memory, we can access
each character in the string by their positions. This is referred to as the
indexing operation.
String characters are accessed in the format var[k] where var is the variable
name while k is the position of the character in the string using a zero-based
indexing scheme such that k = 0 for the first character and k = N-1. N is the
length of the string.
Python strings can be indexed from the front or the rear of the string. For
front indexing, the index I positive while it is negative for rear indexing.

1 >>> dept = "Computer Science"


2 >>> print dept[0], dept[6], dept[3]
3 C e p
4 >>> print dept[-1], dept[-2], dept[-3]
5 e c n
Processing String Data
String Slicing
Another operation made possible by strings’ sequential storage nature is the
SLICING operation.
Slicing allows for strings to be sectioned and for some other sequences to be
fetched from a string.
A string X can be sliced as follows;

X[ k : n ], all characters from index k to index n-1

 X[ k : ], all characters from index k to the end of the string

 X[ : k ], all characters from the beginning of the string to index k-1


 X[ k : n : m], all characters from index k to index n-1 at step m, when k <

n, m is +ve, when k > n then m must be –ve.


Processing String Data

1 >>> dept = “Computer Science”


2 >>> dept[:3]
3 'Com'
4 >>> dept[0:5]
5 'Compu‘
6 >>> dept[0:17]
7 'Computer Science‘
8 >>> dept[0:17:2]
9 'Cmue cec‘
10 >>> dept[17:0:-1]
11 'ecneicS retupmo'
12 >>> dept[17:0:-3]
13 'eeSep‘
14 >>> dept[4:-1:1]
15 'uter Scienc‘
16 >>> dept[::-1]
17 'ecneicS retupmoC'
Processing String Data
Conversion functions
str(var) – converts var of basic types e.g. integer, floats and objects to string
ord(var) – returns the ASCII code of the var
chr(var) – returns the ASCII character of the var

1 >>> ord('A'), ord('a')


2 (65, 97)
3 >>> ord('Q'), ord('x')
4 (81, 120)
5 >>> ord('#'), ord('+')
6 (35, 43)
7 >>> chr(66),chr(70),chr(30),chr(100),chr(98)
8 ('B', 'F', '\x1e', 'd', 'b')
9 >>> chr(200),chr(69),chr(21),chr(210),chr(111)
10 ('\xc8', 'E', '\x15', '\xd2', 'o')
Processing String Data
Immutability of Strings
By default, python strings are immutable.
Immutability is the characteristic of strings that states that a string cannot
be modified once it is created.
So to change a string, it is better to create a new one.

1 >>> dept = "Computer Science"


2 >>> dept[0] = "Department of“
3 Traceback (most recent call last):
4 File "<pyshell#130>", line 1, in <module>
5 dept[0] = "Department of"
TypeError: 'str' object does not support item
6
assignment
7 >>> dept2 = "Department of " + dept
8 >>> dept2
9 'Department of Computer Science'
10
Processing String Data

String formatting
It is also possible to build new strings out of many text values using string
formatting expressions or the format() method of the string object.
Using format expression:
The syntax of this type is
“<string expression with format specifiers>” % (var1, var2…varn)
Supported format specifiers are %d for integers, %f for floats, and %s for
string data.
Example: “There are %d departments in %s” % (10, “SOS”) where %d =>
10, and %s=>”SOS”
1 >>> num , school = 8, "SOS“
2 >>> "There are %d departments in %s" % (num, school)
3 'There are 8 departments in SOS'
Processing String Data

Using format() method:


This involves the calling of the format() on a format string object and then
pass in the values to format with as parameters.
Syntax is:
<string expression with format placeholders>”.format(var1, var2..)
Supported specifiers identified by a sequential zero-based indexing
placeholders.
The format placeholders are in the format “{k}” or “{k:fmt}” where k is a
zero-based index representing the position of the object to replace it with
in the list of parameters and fmt is any of “d”, ”f”, and ”s” depending on
the type of the corresponding data/object in the parameter list.
Example: “There are {0} departments in {1} “.format(10, “SOS”)

Example: “There are {0:d} departments in {1:s} “.format(10, “SOS”)


Processing String Data

For example:
1 >>> num , school = 8, "SOS“
2 >>> "There are {0} departments in {1}“.format(num, school)
3 'There are 8 departments in SOS‘
>>> name = "FUTA"
>>> vc = "Prof. A.G. Daramola"
>>> rating = 8.89
>>> out = "The VC of {0:s} is {1:s}, his team is rated
{2:f}"
>>> print out.format(name, vc, rating)
The VC of FUTA is Prof. A.G. Daramola, his team is rated
9.560000
Processing String Data
String Methods
In memory, everything in python is actually treated as objects that can have
methods, and properties. When treated as objects, strings provides a set of
methods (functions) that can be used to perform so many basic operations
with strings. See table below for some of these;
Method Use
s.capitalize() Capitalizes first character of s
s.count(sub) Count the number of occurrence of sub in s
s.find(sub) Returns the first sub is present in s
s.format(*fmt) Format s with the list of format specifiers fmt
s.index(sub) Returns the first index where sub occurs in s
s.endswith(sub) Returns True if sub ends s and False otherwise
s.join(iterable) Uses s to concatenate the list of items in iterable
s.startswith(pre) Returns True if sub begins s and False otherwise
s.lower() Converts s to lower case string
Processing String Data
String Methods

Method Use
s.isalnum() Checks to if s is alphanumerics
s.isalpha() Checks to if s is all alphabets
s.rstrip(char) Remove all occurrences of char from the right of s
s.isdigit() Checks to if s is a number
s.swapcase() Toggles the case of characters in s
s.split(sep) Breaks the content of s into a sequence using the separator sep
s.strip(char) Remove all occurrences of char from the right and left sides of s
s.upper() Converts s to upper case
s.title() Capitalizes the first letter of each word in s
s.replace(x,y) Replaces all occurrences of x with y in s
Processing String Data
Examples
1 >>> s = "---A biro is a pen, but not all pens are
2 biros----"
3 >>> s.capitalize()
4 '---a biro is a pen, but not all pens are biros----'
5 >>> s.count('biro')
6 2
7 >>> s.find('pens')
8 32
9 >>> s.index('pens')
10 32
11 >>> s.index('biros')
12 41
13 >>> s.endswith('biros')
14 False
15 >>> ','.join(["SOS","SAAT","SET","SMES","SEET","SMAT"])
16 'SOS,SAAT,SET,SMES,SEET,SMAT'
Processing String Data
Examples
1 >>> s[3 : s.index('n')+1]
2 'A biro is a pen'
3 >>> s[3 : s.index('n')+1].lower()
4 'a biro is a pen'
5 >>> s[s.index('n')+3 : len(s)-3].lower()
6 'but not all pens are biros-'
7 >>> s[s.index('n')+3 : len(s)-4].upper()
8 'BUT NOT ALL PENS ARE BIROS'
9 >>> '3'.isalnum()
10 True
11 >>> s.rstrip('-')
12 '---A biro is a pen, but not all pens are biros‘
13 >>> s.replace('biro','Bic')
14 '---A Bic is a pen, but not all pens are Bics----'
Comparative Programming (CSC 202)

LECTURE 6
Python Data Structures I
Lists, and List Comprehension
Lists Data Structure: Features
The list data structure is analogous to famous array data structures in
many programming languages.
Just like strings python list are a sequence structure in that they are
stored in sequential memory location.
Lists are a useful data structure for storing a collection of data. They
can be used to keep a collection of integers, real numbers, strings, and
other objects.
Syntax :
list_name = [ item_0, item_1, item_2….. item_N ]

The first element of a list is stored at index 0, the second at index 1


and the last occupying index (N-1), where N is the total number of
elements in the list. However from the rear, the indices is counted from
-1, -2 ……..to –N!
Lists Data Structure: Features
Lists are very flexible and heterogeneous: they can contain any mix of
data types, strings, numbers, objects, and other lists.

Lists are mutable objects: you can change the content of a list in-
place by assignment to offsets and slices. They can also be modified via
method calls, deletion, and insertion.

Lists are variable-length: the number of elements in a list is not


bounded.
Lists Data Structure: Operations

List Creation
scores = [23,67,32,45,22]
sos_depts = [‘csc’, ’mts’, ’che’, ‘mcb’, ‘phy’, ‘sta’, ‘gns’, ‘bch’]
mix= [50, ‘dog’, 35.82, “manutd”]
multi_list = [ [34,67,22] , [89,23] , [34,21,56] ]

Len() function
The len() function is handy for computing the total number of items
in the list.
len(scores) => 5

List Concatenation
Just like strings, two or more lists can be combined together to form
a larger list.
scores = [23,67] + [32,45,22] => [23,67,32,45,22]
Lists Data Structure: Operations

List Repetition
With repetition, the content of a list object can easily duplicated.
Handy for multi item initialization where there’s a need to initialize
all items in a list to a particular default value.
game_score = [0] * 4 => [0,0,0,0]
[‘go!’] * 4 => [‘go!’, ‘go!’, ‘go!’, ‘go!’]

List Membership
This operation is used to check if a value is a member of list of
items.
>>> ages = [30,20,34,22,67]
>>> 22 in ages => True
>>> “A” in ages => False
Lists Data Structure: Operations
List Indexing
Since lists are sequential structures, we can easily access list items
by their indices/position using zero-based indexing.
>>> Score = [56,87,35,99]
Score[0] 56
Score[1] 87
Score[2] 35
87
99 Score[0]
Score[3]

>>> Score = [87,[12,90],35,99] Score[1]


12 Score[1][0]
90 Score[1][1]

35
Score[2]
99
Score[3]
Lists Data Structure: Operations
List Slicing
Slicing is a major operation on lists that allows sections of list to be
extracted. Just like list slices can be extracted as follows;

list_name[ k : n ], all items from index k to index n-1

list_name[ k : ], all items from index k to the end of the items


list_name[ : k ], all items from the beginning of the items to index k-1
 list_name[ k : n : m], all items from index k to index n-1 at step m,

when k < n, m is +ve, when k > n then m must be –ve.


1 >>> Score = [56,87,35,99]
2 >>> Score[1:3], Score[2:]
3 ([87, 35], [35, 99])
Lists Data Structure: Operations
Creating Matrices
Lists can be used to create multi-dimensional arrays such as
matrices with no limit to the number of the dimensions.

1 >>> matrix = [[45,23,7,-1],[56,22,51,89],[23,56,77,80]]


2 >>> matrix[0], matrix[2]
3 ([45, 23, 7, -1], [23, 56, 77, 80])
4 >>> matrix[1][3], matrix[2][0]
(89, 23)
Lists Data Structure: Operations
List Insertions
Items or sub-lists can be inserted anywhere in a list using slices and
indexing.

1 >>> vals = [23,30,10,-3,5,100,21]


2 >>> vals[1:2] = [11]
3 >>> vals
4 [23, 11, 10, -3, 5, 100, 21]
5 >>> vals[6:6] = [-2,-4]
6 >>> vals
7 [23, 11, 10, -3, 5, 100, -2, -4]
8 >>> vals[5] = [200,300,45]
>>> vals
[23, 11, 10, -3, 5, [200, 300, 45], -2, -4]
Lists Data Structure: Operations
Lists Methods
Lists are by default objects and so provides a set of methods (functions) that
can be used to perform so many basic operations with list items. See table
below for some of these;
Method Use
l.append() Adds an item to the end of the list
l.Sort() Sorts items in a list in order
l.Extend() Adds another list to the end of the l
l.Pop() Removes an item or the item at the rear of a list and return it
l.Reverse() Reorder the items in a list
l.Index() Returns the position of an in the list
l.Insert() Inserts an item or a list at a specified index
l.Remove() Deletes items from the list
Del Another way of deleting items from a list
len Returns the total number of items in the list
Lists Data Structure: Operations

1 >>> L = [12,30,-90,45,32,100]
2 >>> L.append(21)
3 >>> L
4 [12, 30, -90, 45, 32, 100, 21]
5 >>> L.sort()
6 >>> L
7 [-90, 12, 21, 30, 32, 45, 100]
8 >>> L.extend([11,44,33])
>>> L
[-90, 12, 21, 30, 32, 45, 100, 11, 44, 33]
>>> item = L.pop()
>>> item, L
(33, [-90, 12, 21, 30, 32, 45, 100, 11, 44])
>>> item = L.pop(2)
>>> item, L
(21, [-90, 12, 30, 32, 45, 100, 11, 44])
>>> print L.index(30)
2
Lists Data Structure: Operations

1 >>> L.insert(4,-50)
2 >>> L
3 [-90, 12, 30, 32, -50, 45, 100, 11, 44]
4 >>> L.remove(100)
5 >>> L
6 [-90, 12, 30, 32, -50, 45, 11, 44]
7 >>> del L[5]
8 >>> L
[-90, 12, 30, 32, -50, 11, 44]
>>> len(L)
7
Lists Data Structure: Comprehension
List Comprehension
List comprehension is an optimized means of doing more with lists
using less codes. This ensures enhanced code performance, speed
and code understanding. Comprehension allows us to compress
multi-line list processing statements into an efficient single line
code.
1 >>> number = range(1,11)
2 >>> number
3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 >>> even = [i for i in number if (i%2==0)]
5 >>> even
6 [2, 4, 6, 8, 10]
7 >>> odd = [i for i in number if (i%2>0)]
8 >>> odd
[1, 3, 5, 7, 9]
Lists Data Structure: Comprehension

Example
1 >>> times_table = ["%d*%d = %d " % (i,j,(i*j))
for i in range(1,4)
for j in range(1,4)]
2 >>> for item in times_table:
3 print item

5 1*1 = 1
6 1*2 = 2
7 1*3 = 3
8 2*1 = 2
9 2*2 = 4
10 2*3 = 6
11 3*1 = 3
12 3*2 = 6
13 3*3 = 9
Lists Data Structure: Comprehension

Example

1 >>> addition = [i+j for i, j in zip(even, odd)]


2 >>> addition
3 [3, 7, 11, 15, 19]
Comparative Programming (CSC 202)

LECTURE 7
Python Data Structures II
T u p l e s , a n d D i c ti o n a r i e s
Tuple Data Structure: Features
Tuples are a container type of data structure very similar to the
python list data structure.
Tuples are the immutable versions of lists
Tuples are declare using ( and ) instead of [ and ] for lists
Tuples share so many characteristics with lists such as being a
sequence and as well heterogeneous.
Interestingly, tuples can hold lists as items too!
Use the syntax below to create and assign tuples

Syntax :
tuple_id= ( item_0, item_1, item_2….. item_N )

All indexing, slicing and membership operations in lists also applies to


tuples!
Tuple Data Structure: Operations

All indexing, slicing and membership operations in lists also applies to


tuples!

Just like lists built-in functions such as max(), min(), len(), etc are
applicable to tuples

Due to immutability, tuples have only two methods implemented:


count(), and index()
Tuple Data Structure: Operations

1 >>> t = (100,34,89,56,78)
2 >>> max(t)
3 100
4 >>> min(t)
5 34
6 >>> len(t)
7 5
8 >>> sorted(t)
9 [34, 56, 78, 89, 100]
10 >>> t.count(100)
11 1
12 >>> t.index(78)
13 4
Dictionary Structure: Features
Dictionaries are structures that allows you to store data as an
unordered collection of key/value pairs. More specifically, a dictionary
requires 2 lists, one as keys and the other as values.
They can be used as records, or a form of symbol/lookup tables
They are accessed by key and not by offset as every item in a
dictionary has 2 data, the key by which a value can be returned
Items in dictionaries are unordered and are not necessarily stored in
sequential order of addition to the dictionary. In fact items are
scrambled when previewed.
The sequence and slicing operations in lists are not applicable to
dictionaries because they are not sequence structure.
They have variable length and are heterogeneous too
Dictionaries have numerous methods to process their contents.
The key and values can be of any type; integer, strings, floats, objects
or anything data!
Dictionary Structure: Features

Creating a dictionary:
Generally dictionaries are created as follows;
dict_name = {Key_1:Value_1, Key_2:Value_2…..Key_n:Value_n}

Imagine we want to keep a list of departments in SOS as a dictionary of


department code and department names, so that knowing only the
code of the dept can get us the full name of that department.
1 >>> sos = {'csc':'Computer Science',
'mts':'Mathematics', 'che':'Chemistry',
'phy':'Physics', 'bch':'Biochemistry',
'bio':'Biology', 'mcb':'Microbiology',
'sta':'Statistics'}
Dictionary Structure: Operations

Accessing Dictionaries:
Dictionaries are accessed by keys.

For example to get the full name of a department with code ‘csc’
1 >>> sos['csc']
2 'Computer Science‘
3 >>> sos[‘mts']
4 ‘Mathematics‘

To know the total items in a dictionary..


1 >>> len(sos)
2 8
Dictionary Structure: Operations

You can also do Membership by Key on dictionaries too


1 >>> 'eee' in sos
2 False
3 >>> 'mcb' in sos
4 True

To know the total items in a dictionary..


1 >>> len(sos)
2 8

Get the list of all keys and values


1 >>> sos.keys()
2 ['bio', 'phy', 'bch', 'che', 'mts', 'mcb', 'csc', 'sta']
>>> sos.values()
3 ['Biology', 'Physics', 'Biochemistry', 'Chemistry',
4 'Mathematics', 'Microbiology', 'Computer Science',
'Statistics']
Dictionary Structure: Operations

Modifying a dictionary
1 >>> sos['mts'] = 'Mathematical Science'
2 >>> sos
3 {'bio': 'Biology', 'phy': 'Physics', 'bch':
'Biochemistry', 'che': 'Chemistry', 'mts':
'Mathematical Science', 'mcb': 'Microbiology',
'csc': 'Computer Science', 'sta': 'Statistics'}

Delete an entry from a dictionary


1 >>> del sos['sta']
2 >>> sos
3 {'bio': 'Biology', 'phy': 'Physics', 'bch':
'Biochemistry', 'che': 'Chemistry', 'mts':
'Mathematical Science', 'mcb': 'Microbiology',
'csc': 'Computer Science'}
Dictionary Structure: Operations

Getting all items as a list of tuples


1 >>> sos.items()
2 [('bio', 'Biology'), ('phy', 'Physics'), ('bch',
3 'Biochemistry'), ('che', 'Chemistry'), ('mts',
4 'Mathematics'), ('mcb', 'Microbiology'), ('csc',
'Computer Science'), ('sta', 'Statistics')]

Extending dictionaries using the update() method;


1 >>> sos_new = {'bte':'Biotechnology','bot':'Botany'}
2 >>> sos.update(sos_new)
>>> sos
{'bte': 'Biotechnology', 'bio': 'Biology', 'phy':
'Physics', 'bch': 'Biochemistry', 'che':
'Chemistry', 'mts': 'Mathematics', 'bot': 'Botany',
'mcb': 'Microbiology', 'csc': 'Computer Science',
'sta': 'Statistics'}
Dictionary Structure: Operations

Dictionaries also support the pop() method


1 >>> sos.pop('bte')
2 'Biotechnology'
3 >>> sos
4 {'bio': 'Biology', 'phy': 'Physics', 'bch':
'Biochemistry', 'che': 'Chemistry', 'mts':
'Mathematics', 'bot': 'Botany', 'mcb':
'Microbiology', 'csc': 'Computer Science', 'sta':
'Statistics'}

Iterating on dictionary items is possible, python iterates over the


keys by default, though you can choose to iterate over values
instead.
Dictionary Structure: Operations

1 >>> products = {100:'Tooth Brush', 200:'Red Wine',


2 300:'Hobnobs', 400:'Futa Bread'}
3
4 >>> for product_id in products:
print product_id

200
300
400
100
>>> for product_id in products:
print "%d => %s " % (product_id,products[product_id])

200 => Red Wine


300 => Hobnobs
400 => Futa Bread
100 => Tooth Brush
Dictionary Structure: Operations

Using dictionaries as records


1 >>> student = {'name':'Ade Uche Musa',
'matno':'CSC/08/2384', 'sex':'Male', 'hobbies':
['Football','Chess','Gymnastic','Dancing'], 'phone':
['08193736622','08036636677'], 'email':'[email protected]'}
>>> student
2 {'name': 'Ade Uche Musa', 'sex': 'Male', 'phone':
3 ['08193736622', '08036636677'], 'hobbies': ['Football',
'Chess', 'Gymnastic', 'Dancing'], 'email':
'[email protected]', 'matno': 'CSC/08/2384'}
>>> student['name']
4 'Ade Uche Musa'
5 >>> for field in student:
6 print field,
7
name sex phone hobbies email matno
8
Dictionary Structure: Operations

Using dictionaries as records


1 >>> for field in student:
2 print student[field]

3 Ade Uche Musa


4 Male
5 ['08193736622', '08036636677']
6 ['Football', 'Chess', 'Gymnastic', 'Dancing']
7 [email protected]
8 CSC/08/2384
Dictionary Structure: Operations

Using dictionaries as records


1 >>> for field in student:
2 if field == 'phone' or field == 'hobbies':
3 print field,": ",
4 for item in student[field]:
print item, ",",
print "\n"
else:
print field, ":",student[field]

name : Ade Uche Musa


sex : Male
phone : 08193736622 , 08036636677 ,
hobbies : Football , Chess , Gymnastic , Dancing ,
email : [email protected]
matno : CSC/08/2384
Comparative Programming (CSC 202)

LECTURE 8
Working with Python Modules
Working with Modules
Python lets you break code down into reusable functions and classes;
then reassemble those components into modules and packages. The
larger the project, the more useful this organization

A module (i.e. a reusable piece of software) is a file containing Python


code (i.e. Python definitions and statements)

The file name is the module name with the suffix .py appended.
Within a module, the module’s name (as a string) is available as the
value of the global variable _name_.

Many related modules can be grouped together into a collection


called a package.
Working with Modules

Advantages / Benefits of Using Modules

It allows you to logically organize your Python code.

Grouping related code into a module makes the code easier to


understand and use.

It improves code maintainability.

Error containment i.e. it confines program error (s) to a section of the


code.

It ensures code reusability.


Working with Modules

Type of Python Modules


-Standard Library Modules: is provided as part of the core Python
language and located at C:\Python27\Lib on Windows
-User-defined Modules: usually created by Python developers or
programmers.

Defining a Module
Recall from Lecture 4: the function that accept student’s name and
print a greeting message:
def greet(name) :
print “How are you? ”+name
Note: saving this code with a name such as greeting.py automatically
makes it a module that may be imported and use in another module/
program.
Working with Modules

The import Statement:


Any Python source file can be used as a module by executing an import
statement in some other Python source file. Three options are
available:

1. Importing Modules from the Same Directory (or Folder): -

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

The execution of the above statement imports module1 provided it is


available in the search path.
A search path is a list of directories that the interpreter searches before
importing a module. In this case, it will include the path to the current
working directory where the current program file is saved.
Working with Modules

-At least one module name must be specified at the execution of the
import statement, the square bracket in the syntax means the second
to the nth module are optional.
-After importation, you can access the names in the module using dot
notation.

-Example: Write a Python program to import and use the greeting.py


module defined above.
Module Name : greeting.py

def greet(name) :
print "How Are You Doing Mr " + name + " ?"
Working with Modules

Main_Program : main.py
import greeting
greeting.greet("Student")

OUTPUT:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32Type
"copyright", "credits" or "license()" for more information.
>>> ============================ RESTART ===========================
>>> How Are You Doing Mr Student ?
>>>
Working with Modules
-Example:

quadratic equation defined as 𝑎𝑥2 + 𝑏𝑥+ 𝑐 = 0 will have a complex


Write a Python program that uses a module to test whether a given

roots, real and equal roots or a real and distinct roots where
𝑥=
−𝑏±ξ𝑏2−4𝑎𝑐
2𝑎
.
Module Name : nature_of_root.py

def determine_the_nature(a, b, c) :
disc = b * b - 4 * a * c
if (disc == 0):
return 0
elif (disc > 0):
return 1
else:
return -1
Working with Modules
Main_Program : quadratic.py
import nature_of_root
a = raw_input("Enter a Number for A: ")
a = int(a)
b = raw_input("Enter a Number for B: ")
b = int(b)
c = raw_input("Enter a Number for C: ")
c = int(c)
return_val = nature_of_root.determine_the_nature(a, b, c)
if (return_val < 0):
print ("The Roots Are Complex !")
elif (return_val == 0):
print("The Roots Are Real and Equal !")
else:
print("The Roots Are Real and Distinct !")
Working with Modules
Output:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32Type
"copyright", "credits" or "license()" for more information.
>>> ============================== RESTART ===============================
>>>
Enter a Number for A: 2
Enter a Number for B: 4
Enter a Number for C: 2
The Roots Are Real and Equal !
>>>
Working with Modules

2. Importing Names into the Current Namespace:


-allows you to import names from modules in the same directory into
the current namespace.
-Syntax:
from ModuleName import Name1 [, Name2 [, ... NameN ]
Example 3: Repeat example 2 using the syntax just discussed.
Module Name : nature_of_root.py
The code is the same as the one above

Main_Program : quadratic.py
The code also remains the same but the import statement:
import nature_of_root
changes to
from nature_of_root import determine_the_nature
Working with Modules

3. Import Modules from Different Directories


- When you import a module, the Python interpreter searches for the
module in the current directory. If not found then Python search every
directory in the Python path and if this also fails, then Python checks
the default path e.g. C:\Python27 on Windows.

-The code for Python standard libraries is installed in default path.

-Python stores a list of the directories that it searches in sys.path.

- Simply put, importing from different directories implies importing


from different packages.
Working with Modules
-A package contains related modules, sub-packages, sub-sub-packages
and so on.
-You can access module inside a package using dot notation e.g.
- if module nature_of_root.py were saved in myPythonCodes, you
will access it as:
myPythonCodes.nature_of_root.determine_the_nature(a, b, c)
where myPythonCode is the package name, nature_of_root is the
module name and determine_the_nature(a, b, c) is the function
name.
-To import a module from a different package, create an empty Python
file _init_.py and save it in the package you want to import from.
-The script _init_.py runs when the package is imported.
Working with Modules

Example 4: Considering example 2, rewrite the Python code to


demonstrate how to import modules from a different package.
-The module nature_of_root.py is saved in myPythonCodes directory
or package.
- An empty Python file _init_.py is created and also saved in
myPythonCodes.
-The main program quadratic.py is saved in Python root directory
Module Name : nature_of_root.py
The code is the same as the one above

Main_Program : quadratic.py
The code also remains the same but the import statement:
import nature_of_root
changes to
from myPythonCodes.nature_of_root import determine_the_nature
Working with Modules
Output:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32Type
"copyright", "credits" or "license()" for more information.
>>> ============================== RESTART ===============================
>>>Enter a Number for A: 3
Enter a Number for B: 2
Enter a Number for C: 5
The Roots Are Complex !
>>>
Comparative Programming (CSC 202)

LECTURE 9
Object-Oriented Python I
C l a s s e s , P r o p e r ti e s , a n d M e t h o d s
Object Oriented Python
Classes allow you to modify a program without really making changes to it

• A user –defined type (a new type) is called a class

• A class is defined using syntax:


class name:
"documentation"
statements
-or
class name(base1, base2, ...):

...
• Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
• May also be class variable assignments
Object Oriented Python
Instancing a class:
>>> import fibonacci2
>>> fib = fibonacci2.Fib(100) ①
>>> fib ② <fibonacci2.Fib object at 0x00DB8810>
>>> fib.__class__ ③ <class 'fibonacci2.Fib'>
>>> fib.__doc__ ④ 'iterator that yields numbers in the Fibonacci sequence'

You are creating an instance of the Fib class (defined in the fibonacci2 module) and assigning the
newly created instance to the variable fib. You are passing one parameter,100, which will end up
as the max argument in Fib’s __init__() method.

fib is now an instance of the Fib class.

Every class instance has a built-in attribute, __class__, which is the object’s class. Java
programmers may be familiar with the Class class, which contains methods like getName()
and getSuperclass() to get metadata information about an object. In Python, this kind of metadata
is available through attributes, but the idea is the same.

You can access the instance’s docstring just as with a function or a module. All instances of a
class share the same docstring.
Object Oriented Python
Example9.1: We create a class Point
>>> class Point (object):
"""Here goes the body"""
– A new class ‘Point’ is created, which is a kind of object,
which is a built-in type.
– Defining a class named Point creates a class object
– The class object is like a factory for creating objects
>>> dot=Point()
>>> blank=Point()
>>> mark=Point()
– A value can be assigned to an instance of a class
using dot notation thus:
>>> blank.x=3.0
>>> blank.y=4.0
Object Oriented Python

– Dot notation can be used as part of any


expression:
>>>print ‘(%g, %g)’ % ( blank.x, blank.y )
– An instance can be passed as an argument
thus:
Example 9.2:
>>> class Rectangle (object):
""“Represents a rectangle""“
attributes: width, height, corner.

"""Here goes the body"""


Comparative Programming (CSC 202)

LECTURE 10
O b j e c t- O r i e nte d P y t h o n I I
A c c e s s s p e c i fi e r s , I t e r a t o r s , G e n e r a t o r s
Object Oriented Python

Access Specifiers

-Unlike other OOP languages, access modifiers or specifiers like public,


private, etc are not explicit.
-You don’t need to specify them declaratively
Object Oriented Python

ITERATORS and GENERATORS


• Generators and Comprehensions are just simple form of iterators

Understanding Python Iterables and Iterators: A couple of definitions

• Iterable - A container is said to be iterable if it has the __iter__ method

defined.

• Iterator - An iterator is an object that supports the iterator protocol which

basically means that the following two methods need to be defined.


 It has an __iter__ method defined which returns itself.
 It has a next method defined (__next__ in Python 3.x) which returns
the next value every time the next method is invoked on it.
Object Oriented Python
Example 10.1: Consider a list. A list is iterable, but a list is not its own iterator.

The iterator of a list is actually a listiterator object. A listiterator is its own iterator.
Object Oriented Python

How To Make Your Object An Iterable:

Program Output:
Object Oriented Python
Example 10.2: For a more practical example. Let us say you are implementing a game of cards
and you have defined a card and a deck as follows:

Now to iterate over the cards in the deck, you have to do ...

But Deck is a container that has multiple cards. Wouldn’t it be nice if we could just write for c
in Deck() instead of writing for c in Deck().cards? Let’s try that!
Object Oriented Python
Let’s try the syntax again.

Oops! It doesn’t work. For the syntax to work, we need to make Deck an iterable. It is in
fact very easy. We just need to add an __iter__ method to our class that returns an
iterator.

...#Works perfectly. That’s it!


Object Oriented Python
A Fibonacci Iterator is given in the following example:
• An iterator is just a class that defines an _iter_() method
Object Oriented Python

To build an iterator from scratch, Fib needs to be a class, not a function.

“Calling” Fib(max) is really creating an instance of this class and calling
its __init__() method with max. The __init__() method saves the maximum value as an
instance variable so other methods can refer to it later.

The __iter__() method is called whenever someone calls iter(fib). (As you’ll see in a minute,
a for loop will call this automatically, but you can also call it yourself manually.) After
performing beginning-of-iteration initialization (in this case, resetting self.a and self.b, our
two counters), the __iter__() method can return any object that implements
a__next__() method. In this case (and in most cases), __iter__() simply returns self, since this
class implements its own __next__() method.
Object Oriented Python

The __next__() method is called whenever someone calls next() on an iterator of an instance
of a class. That will make more sense in a minute.

When the __next__() method raises a StopIteration exception, this signals to the caller that
the iteration is exhausted. Unlike most exceptions, this is not an error; it’s a normal
condition that just means that the iterator has no more values to generate. If the caller is
a for loop, it will notice this StopIteration exception and gracefully exit the loop. (In other
words, it will swallow the exception.) This little bit of magic is actually the key to using
iterators in for loops.

To spit out the next value, an iterator’s __next__() method simply returns the value. Do not
use yield here; that’s a bit of syntactic sugar that only applies when you’re using generators.
Here you’re creating your own iterator from scratch; use return instead.
Object Oriented Python

• A function that contains a yield statement is called a generator function.


• A generator function is an ordinary function object in all respects, but has the
new CO_GENERATOR flag set in the code object's co_flags member.
• When a generator function is called, the actual arguments are bound to
function-local formal argument names in the usual way, but no code in the
body of the function is executed.
• Instead a generator-iterator object is returned; this conforms to the iterator
protocol, so in particular can be used in for-loops in a natural way.
• NB: When the intent is clear from context, the unqualified name "generator"
may be used to refer either to a generator-function or a generator- iterator.
Object Oriented Python

• Each time the .next() method of a generator-iterator is invoked, the code in the
body of the generator-function is executed until a yield or return statement
(next slide) is encountered, or until the end of the body is reached.

• If a yield statement is encountered, the state of the function is frozen, and the
value of expression_list is returned to .next()'s caller.

• By "frozen" we mean that all local state is retained, including the current
bindings of local variables, the instruction pointer, and the internal evaluation
stack: enough information is saved so that the next time .next() is invoked, the
function can proceed exactly as if the yield statement were just another
external call.
Object Oriented Python

Restriction:
A generator cannot be resumed while it is actively running:
>>> def g():
... i = me.next()
... yield i
>>> me = g()
>>> me.next()
Traceback (most recent call last):
...
File "<string>", line 2, in g

ValueError: generator already executing


Object Oriented Python
• A generator function can also contain return statements
of the form: "return“
>>> def f1():
... try:
... return
... except:
... yield 1
>>> print list(f1()) []
Object Oriented Python
• Generators and Exception Propagation
>>> def f():
... return 1/0
>>> def g():
... yield f()
# the zero division exception propagates
... yield 42
# and we'll never get here
>>> k = g()
>>> k.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in g
File "<stdin>", line 2, in f ZeroDivisionError: integer division or modulo by zero
>>> k.next() # and the generator cannot be resumed
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
Object Oriented Python

• Generators are a simple and powerful tool for creating iterators


– They are written like regular functions but use the yield statement whenever they
want to return data

– Each time next() is called, the generator resumes where it left-off (it
remembers all the data values and which statement was last executed)
Object Oriented Python
Generator Expressions
Generator expressions are more compact but less versatile than full generator
definitions and tend to be more memory friendly than equivalent list
comprehensions.
Comparative Programming (CSC 202)

LECTURE 11
O b j e c t- O r i e nte d P y t h o n I I I
Inheritance and Method Overloading
Object Oriented Python

INHERITANCE
• An instance of a class inherits the attributes of that class.
• However, classes can also inherit attributes from other classes.
• Hence, a subclass inherits from a superclass allowing you to make
a generic superclass that is specialized via subclasses.
• The subclasses can override the logic in a superclass, allowing you
to change the behavior of your classes without changing the
superclass at all.
Object Oriented Python
Inheritance Syntax:

• The name BaseClassName must be defined in a scope containing the derived class
definition

• Python has two built-in functions that work with inheritance:


• Use isinstance () to check an instance’s type: isinstance(obj, int) will be True only
if obj.__class__ isintor some class derived from int.
• Use the function issubclass() to check class
inheritance: issubclass(bool, int) is True since bool is a subclass of int.
However, issubclass(unicode, str) is False since unicode is not a subclass
of str (they only share a common ancestor, basestring)
Object Oriented Python
A simple Class example:
Object Oriented Python

Example in practice:
>>>f = FirstClass() #Instance of FirstClass
>>>s = SecondClass() #Instance of SecondClass
>>>f.setdate(“This is CSC 202 Class-Python”)
>>>s.setdata(“A-70% Sure for Effikos!”)
>>>f.display()
>>>This is CSC 202 Class-Python
>>>s.display()
>>>A-70% Sure for Effikos!
• Both instances (f and s) use the same setdata method from FirstClass;
• f uses it because it’s an instance of FirstClass while s uses it because
SecondClass inherits setdata from FirstClass.
• However, when the display method is called, f uses the definition from
FirstClass but s uses the definition from SecondClass, where display is
overridden.
Object Oriented Python

• Classes allow for modification of a program without really


making changes to it.
• To elaborate, by sub classing a class, you can change the
behavior of the program by simply adding new components
to it rather than rewriting the existing components.
• Class objects support two kinds of operations: attribute
references and instantiation.

• The other kind of instance attribute reference is a method.


– A method is a function that “belongs to” an object of a class.
– When a class defines an __init__() special method, class instantiation
automatically invokes __init__() for the newly-created class instance(i.e object)
– the __init__() method may have arguments for greater flexibility
Object Oriented Python

• For example lets define a Complex class, instantiate an object of it


and then see how to call properties/attributes of the object.
Object Oriented Python
Multiple Inheritance

A class definition with multiple base classes looks like this in Python:

Name mangling is helpful for letting subclasses override methods without


breaking intra-class method calls.

For example:
Object Oriented Python
Object Oriented Python
Operator overloading
• Simply means that objects that you create from classes can respond to actions (operations)

that are already defined within Python, such as addition, slicing, printing, etc.

• Even though these actions can be implemented via class methods, using overloading ties

the behavior closer to Python’s object model and the object interfaces are more consistent

to Python’s built-in objects, hence overloading is easier to learn and use.

• User-made classes can override nearly all of Python’s built-in operation methods.

• These methods are identified by having two underlines before and after the method

name, like this: __add__.

• These methods are automatically called when Python evaluates operators; if a user class

overloads the __add__ method, then when an expression has “+” in it, the user’s method

will be used instead of Python’s built-in method.


Object Oriented Python
Comparative Programming (CSC 202)

LECTURE 12
A d va n c e d P y t h o n
H a n d l i n g E r r o r s & E x c e p ti o n s
Handling Errors & Exception
Python generates two types of errors
Syntax Errors: occurs when python is unable to understand a line of
instruction. A program containing a syntax error will never be
executed. An example is using a keyword as a variable name.
print = 34 # print is a keyword
if a = b # use of single ‘=‘ and omission of ‘:’
print a,b

Exceptions: these are errors that occur when python knows what to
do with a piece of code but cannot perform the action due to the
violation of some defined rules about such operations/actions. e.g.
-division by zero,
-accessing the web when the internet connection is not available
-trying to open a file that is opened in another program.
-trying to use a textual data where a numeric is expected
Handling Errors & Exception

Exceptions
While syntax errors often lead your program to crash or terminate
prematurely, exceptions may not necessarily terminate your program
unexpectedly.
Syntax errors are often as a result of violating rules of writing valid
programs in a programming language, exceptions are often as a result
of violating rules defined by the application requirements.
Unlike syntax errors, users can define their own exceptions and write
programs to handle them if/when they occur.

Python provides a means to handle exceptions using the try……except


block.
It is always advisable to place any suspicious lines of codes in a
try….except block to handle any foreseen error!
Handling Errors & Exception

How to handle python exceptions


The syntax of the try….except block is;
try:
<python statements>
<python statements>
except:
<python statements>
<python statements>
When python executes a program containing a try block, it will attempt
to execute the code under the try block, if there is an error with that
block, the python interpreter will jump to code under except block and
then execute it.
-exceptions provide a clean means for your program to degrade
gracefully by displaying a clean error message!
Handling Errors & Exception

Example
Notice the unfriendly error generated without the try…except block

1 >>> radius = float(raw_input("What is the radius of the


Circle? "))
2 area = 3.142 * radius * radius
3 print area

4 What is the radius of the Circle? he

5 Traceback (most recent call last):


6 File "<pyshell#364>", line 1, in <module>
radius = float(raw_input("What is the radius of the
Circle"))
7 ValueError: could not convert string to float: he
8 >>>
Handling Errors & Exception

Example
Notice the friendly message displayed with the use of the try…except
block
1 >>> try:
2 radius = float(raw_input("What is the radius of the
Circle? "))
3 area = 3.142 * radius * radius
4 print area
5 except:
6 print "Radius must be numeric!"

7 What is the radius of the Circle? he


8 Radius must be numeric!
>>>
Handling Errors & Exception

Example
1 >>> try:
2 radius = float(raw_input("What is the radius of the
Circle? "))
3 area = 3.142 * radius * radius
4 print area
5 except:
6 print "Radius must be numeric!"

7 What is the radius of the Circle? 45


8 6362.55
>>>
Comparative Programming (CSC 202)

LECTURE 13
A d va n c e d P y t h o n
Python Standard Libraries
Python Standard Library

Recall from Chapter Five – Python Modules:


- Python lets you break code down into reusable functions and
classes; then reassemble those components into modules and
packages. The larger the project, the more useful this organization
- Asides Python user-defined modules, Python also provide a
collection of module, the Standard Library, as part of the core Python
Language.
- Just as a module groups related definitions (i.e. classes, functions or
data that perform specific, related tasks), a package groups related
modules.
Python Standard Library

Advantages of Python Standard Library


- It provides programmer with functions that perform common task
such as mathematical calculation, string manipulation, e.t.c.
- It simplifies programmers’ work because they need not to write
functions to perform the common tasks.
- It promotes the concept of code reusability, code maintainability,
code portability, error containment, e.t.c.
- It encourages cross-platform (i.e. platform independence)
programming e.g. modules written in C are packaged as part of the
Python Standard Library Codes.
Python Standard Library

The Python’s Standard Library cover a wide range of modules;


typical examples are:
- math: -
- random
- os : - provides file and process operation
- datetime: - provides functions to work with dates and
times.
- re: - provides regular expression support for Python.
Regular expressions are string patterns written in a special
syntax, which can be used to match strings and extract
substrings.
Python Standard Library
The math Module
- Implements a number of mathematical operations for floating-point
numbers. Some of the methods or functions in this module are:
Methods Description
pow (x, y) Return x**y.

floor (x) Return the floor of x as a float, the largest integer value less than or equal to x.

ceil (x) Return the ceiling of x as a float, the smallest integer value greater than or equal
to x.
cos (x) Return the hyperbolic cosine of x.
degrees (x) Converts angle x from radians to degrees.
log 10(x ) Return the base-10 logarithm of x.
log (x [, base]) Return the logarithm of x to the given base.
hypot (x, y) Return the Euclidean norm, sqrt(x*x + y*y).
exp (x)
Return e**x.
sqrt (x) Return the square root of x
Python Standard Library

1 >>> import math


2 >>> math.pow(2,3)
3 8.0
>>> math.floor(3.6), math.ceil(3.6)
(3.0, 4.0)
>>> math.cos(0.0)
1.0
>>> math.degrees(0.5)
28.64788975654116
>>> math.log10(100), math.log(4,2)
(2.0, 2.0)
>>> math.hypot(4,3)
5.0
>>> math.exp(3)
20.085536923187668
>>> math.sqrt(25)
5.0
Python Standard Library

Note: The module also defines two mathematical constants:

- pi: The mathematical constant pi.


- e: The mathematical constant e.

Example: Write a Python program to find the square root of all the
perfect squares between 1 and n where n is an integer greater than
zero.
Python Standard Library
Filename = perfectSquare.py
import math
list = []
n = raw_input("Enter an Integer Greater Than 0: ")
n = int (n)
for counter in range (0, n):
pSquare = counter * counter
if pSquare > n:
stopCount = counter
break
else:
list.append(pSquare)
print ("------------------- Output ----------------")
for counter in range (0, stopCount):
if (counter <= n):
print ("Square Root of ", list[counter], "is ",math.sqrt(list[counter]))
Python Standard Library
Output:
Enter an Integer Greater Than 0: 10
------------------- Output ----------------
('Square Root of ', 0, 'is ', 0.0)
('Square Root of ', 1, 'is ', 1.0)
('Square Root of ', 4, 'is ', 2.0)
('Square Root of ', 9, 'is ', 3.0)

•The random Module: - The module random introduce the element


of chance into computer application by generating pseudo-random
numbers for various distribution. Some of the functions contained in
this module are:
Python Standard Library
Method Description
random () Return the next random floating point number in the range
(0.0, 1.0).
randrange([start,]stop[,step]) Return a randomly selected element from range(start, stop,
step). This is equivalent to choice(range(start, stop, step)),
but doesn’t actually build a range object
randint (a, b) Return a random integer N such that a <= N <= b.
choice (seq) Return a random element from the non-empty sequence
seq. If seq is empty, raises IndexError.
shuffle(x [,]) Shuffle the sequence x in place. The optional argument
random is a 0-argument function returning a random
float in [0.0, 1.0); by default, this is the function random().
Note that for even rather small len(x), the total number of
permutations of x is larger than the period
of most random number generators; this implies that most
permutations of a long sequence can never be
generated.

uniform (a, b) Return a random real number N such that a <= N < b.
Python Standard Library

1 >>> import random


2 >>> random.choice('FUTA')
3 'T'
>>> random.randrange(0, 101, 2)
48
>>> random.randint(1, 10)
10
>>> items = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> random.shuffle(items)
>>> items
[2, 6, 8, 7, 4, 5, 3, 10, 1, 9]
>>> random.sample(items, 3)
[8, 1, 3]
Python Standard Library

Example:
In a game of chance, a fair die is thrown five times.
The final outcome is the concatenation of the individual samples.

You are expected to predict correctly at least three numbers in the


outcome to be qualified for any benefits.

Write a Python program to simulate this event.


Python Standard Library
Filename = fair_dice_guess.py
import random
list = []
hit = 0
for counter in range(5):
list.append(random.randrange(1,7))
print "------------ Output ------------"
print "Pls Enter Your Prediction As A Group of Five Integer"
print "There Should be No Blank Space : "
myPrediction = str(raw_input("My Prediction : "))
while (len(myPrediction) > 5):
print ("You Cannot Enter More Than 5 Numbers:")
myPrediction = raw_input("My Prediction : ")
myPrediction = str (myPrediction)

for i in range (0, len (list)):


for n in range (0, len (myPrediction)):
if (str(list[i]) == myPrediction[n]):
hit = hit + 1
Python Standard Library
Filename = fair_dice_guess.py
print "Generated Number = ", list
print "Your Prediction = ", myPrediction
print "Your Hits = ", hit
if (hit >= 3):
print "Bravo ! You Guess Right ..."
else:
print "Sorry Looser, You Guess Wrong ..."

Output:
------------ Output ------------
Pls Enter Your Prediction As A Group of Five Integer
There Should be No Blank Space :
My Prediction : 42675
('Generated Number = ', [3, 2, 3, 4, 5])
('Your Prediction = ', '42675')
('Your Hits = ', 3)
Bravo ! You Guess Right...
Python Standard Library
- The datetime Module: The datetime module is one of the three standard
modules (i.e. the time module, the datetime module and the calendar module)
used by Python to manipulate dates and time values in several
representations.
- it includes functions and classes for doing date and time parsing, formatting,
and arithmetic.
- The datetime module exports the following constants:
i. MINYEAR: The smallest year number allowed in a date or datetime object
is 1.
ii. MAXYEAR: The largest year number allowed in a date or datetime object is
9999.

- Attributes of the datetime module are year, month, day, hour, minute, second,
microsecond, and tzinfo.
Python Standard Library
Filename = fair_dice_guess.py

>>> import datetime


>>> tyme = datetime.time(3,5,8)
>>> print tyme
03:05:08
>>> print "Hour : ", tyme.hour
Hour : 3
>>> print "Minute : ", tyme.minute
Minute : 5
>>> print "Second : ", tyme.second
Second : 8
>>> print "Microsecond : ", tyme.microsecond
Microsecond : 0
>>> print "Time Zone Info : ", tyme.tzinfo
Time Zone Info : None
Python Standard Library

The os Module:
- provides a unified interface to a number of operating system functions.

- it provides file and process operations e.g. changing directory, removing files,
e.t.c. and contains lots of functions and other modules e.g. os.path, etc.
- Python os module can also be used to perform tasks such as finding the name
of present working directory, changing current working directory, checking if
certain files or directories exist at a location, creating new directories, deleting
existing files or directories, walking through a directory and performing
operations on every file in the directory that satisfies some user-defined
criteria, and a lot more.

- unlike the os module, the os.path module helps extract directory names, file
names, and extension from a given path (i.e. a directory or file name).
Python Standard Library

- The examples shown below demonstrate how to use the os module


in Python:
Required Assumption: - Suppose we are in a directory
myPythonCodes whose full path is C:\Python27\myPythonCodes
and it has the following structure:
- control_structures
- testwhile.py
- greeting.py
- nature_of_roots.py
- __init__.py
This implies that myPythonCodes contains one directory
control_structures (which contains one a file testwhile.py) and three
files: greeting.py, nature_of_roots.py, __init__.py.
Python Standard Library
Finding Information about the current working directory
- To get the complete path of the current working directory enter:
import os
myPath = str(os.getcwd())
print (myPath)

Output: C:\Python27\myPythonCodes

Alternatively:
import os
myPath = str(os.path.abspath('.'))
print (myPath)
Output: C:\Python27\myPythonCodes
Python Standard Library

- To display a list of all files and directories in the current directory:


import os
displayFiles = str(os.listdir('.'))
print (displayFiles)
Output: ['control_structures', 'greeting.py', 'nature_of_root.py',
'testModule', '__init__.py']
Change to another directory
This can be done by using os.chdir(path_to_new_directory) command. For
example, suppose os.getcwd() returns “C:\Python27\myPythonCodes”. The
current directory is “myPythonCodes” but we intend to make
“Control_Structures” our current directory.
import os
os.chdir('./control_structures')
myPath = str(os.getcwd())
print (myPath)
Python Standard Library
Output: C:\Python27\myPythonCodes\control_structures

-To go back to the parent directory of “control_structures”:


import os
os.chdir('../')
myPath = str(os.getcwd())
print (myPath)

Output: C:\Python27
Python Standard Library
Output: C:\Python27\myPythonCodes\control_structures

-To go back to the parent directory of “control_structures”:


import os
os.chdir('../')
myPath = str(os.getcwd())
print (myPath)

Output: C:\Python27
Python Standard Library

Extracting filename from a given path


- unlike the os module, the os.path module helps extract directory
names, file names, and extension from a given path (i.e. a directory
or file name).
- To extract file name from a given path:
import os
myFileName =
os.path.basename('C:/Python27/myPythonCodes/nature_of_root.py')
myFileName = str(myFileName)
print (myFileName)

Output: nature_of_root.py
Python Standard Library
The re Module:
- a regular expression is an object that matches some collection of strings.
- it can be used to search and transforms strings but uses their own special
syntax to describe strings to match.
- the module re provides full support for Perl-like regular expressions in
Python.
- The functions in this module let check if a particular string matches a given
regular expression.
- regular expression can contain both ordinary characters (e.g. A,..,Z, a,..,z,
0,..,9) and even special character such as :
i. Dot (‘.’) :- it matches any character except a new line.
ii. Caret (‘^’):- it matches the start of the string
iii.‘*’: - it matches 0 or more characters
iv. ‘+’: - it matches 1 or more characters
v. ‘?’ : - it matches 1 or more character
Python Standard Library

Two of the functions available for handling regular expression


are:
The match Function: This function attempts to match RE pattern
to string with optional flags.
Syntax: re.match (pattern, string, flags=0)
Parameter Description
pattern This is the regular expression to be matched.
This is the string which would be searched to
string
match the pattern at the beginning of string.
You can specifiy different flags using bitwise OR
flags (|). These are modifiers which are listed in the
table below.
Python Standard Library

Note: The re.match function returns a match object on


success, None on failure.

Match Object Methods Description


This methods returns entire match
group(num=0)
(or specific subgroup num)
This method return all matching
groups() subgroups in a tuple (empty if
there weren't any)
Python Standard Library

Example: Write a Python program defining a regular


expression that searches all the words following a hyphen.

>>> import re
>>> myReg = re.search('(?<=-)\w+', 'Programming in-Python27')
>>> myReg.group(0)
'Python27'
Python Standard Library

Example: lets write some program to perform some pattern


macthing..
import re
line = "Comp. Sci. Students are good at writing programs";
objMatched = re.match( r'(.*) are(\.*)', line, re.M|re.I)
if objMatched:
print "objMatched.group() : ", objMatched.group()
print "objMatched.group(1) : ", objMatched.group(1)
print "objMatched.group(2) : ", objMatched.group(2)
else:
print "No match!!"
Output:
objMatched.group() : Comp. Sci. Students are
objMatched.group(1) : Comp. Sci. Students
objMatched.group(2) :
Comparative Programming (CSC 202)

LECTURE 14
A d va n c e d P y t h o n
File Processing
File Processing
Files are an element of storage on your systems that are managed by
the operating system.

Files are used to store information of varying types; images, text,


binary, video, database, program codes etc…

Python provides a built-in object that provides a managed way to


access file resources in your programs and on local or remote computer
systems
The built-in open() function is used to create a python file object
which serves as a link to a file residing on your computer.
Once the open() function has been used, you can then transfer strings
of data to and from the associated file using methods provided by the
file objects.
File Processing

Opening Files
Before working with any file, it must first be opened. The syntax for
opening python files is as follows;
file_handle = open(file_path, file_mode)
file_path: is the path string showing where the file is stored on the local
system e.g ‘C:\python27\codes’
file_mode: is the mode in which the file is to be used. It typically takes
any of the following modes;

Mode Meaning
R Opening a file for reading
W Opening a file for writing, overwrites whatever is the file
A Opening a file for appending data to the end of a file, preserving the
existing content.
File Processing

Opening Files
Now lets try open some a file named ‘poem.txt’ located in ‘C:\
python27\codes\’
1 >>> f = open('c:\python27\codes\poem.txt','r')
2 >>> f
3 <open file 'c:\python27\codes\poem.txt', mode 'r' at
0x022B27B0>

Line 1 opens the specified file object for reading and store a
reference to the file in f
Line 3 shows us information about the opened file such as its full
path, file mode and memory reference.
File Processing
Reading Files
Lets try to read some files;
1 >>> for line in f.readlines():
2 print line
3
OUR AFRICA
Our Africa, virtuous and seated with pride,
Distinct on her gun-throne of glory;
Taking her place amongst her equals;
A vibrant queen – unique in her very own way.
>>> open(r'c:\python27\codes\file2.txt','r').read()
'Federal University of Technology, \nPMB 704\nAkure,\
nNigeria.'
>>> ff = open(r'c:\python27\codes\
file2.txt','r').read()
>>> print ff
Federal University of Technology,
PMB 704
Akure,
Nigeria.
File Processing
Reading Files…
It is also possible to read from a file in byte by byte…
1 >>> ff = open(r'c:\python27\codes\
2 file2.txt','r')
3 # read the first 8 bytes i.e. characters
>>> print ff.read(8)
Federal
# read the next 20 bytes i.e. characters
>>> print ff.read(20)
University of Techn
>>> ff = open(r'c:\python27\codes\poem.txt','r')
>>> print ff.readline()
OUR AFRICA
File Processing
Reading Files…
It is also possible to read from a file its content at once as a
1 >>> ff = open(r'c:\python27\codes\file2.txt','r')
2 >>> list_of_lines = ff.readlines()
3 >>> list_of_lines

[‘Federal University of Technology, \n', 'PMB 704\


n', 'Akure,\n', 'Nigeria.']

>>> for line in list_of_lines:


print line

Federal University of Technology,


PMB 704
Akure,
Nigeria.
File Processing
Example: read a list of scores from a file and then print out the sum and
average of the scores. The file contains 50 scores, each on a separate line.
1 # open the file for reading referenced as ‘ff’
2 >>> ff = open(r'c:\python27\codes\scores.txt','r')
3 # initialised an empty list/array
4 >>> scores = []
5 # iterate through each line, convert to string, remove any
‘\n’ char, then append to the list.
6 >>> for line in ff.readlines():
7 score = int(str(line).lstrip('\n'))
8 scores.append(score)
9 # compute average
10 >>> ave = float(sum(scores))/len(scores)

12 >>> print "Number of students = %d \n Sum = %d \n


Average = %d" % (len(scores), sum(scores),ave)

Number of students = 50
Sum = 3068
Average = 61
File Processing
Writing into Files
Writing into files in python can be performed as shown below;

1 # open the file for writing


2 >>> f = open('c:\python27\codes\greetings.txt','w')
3
# print a line of greeting into the file
>>> f.write("Hey, welcome to my python class!")

# now lets read and display the content of the file


>>> f = open('c:\python27\codes\greetings.txt','r')

>>> f.read()
'Hey, welcome to my python class!'

- We used ‘w’ for writing.


- Writing with ‘w’ overwrites whatever is in the file before.
File Processing
Appending to Files
1 # open the file for appending and then write to the file..
2 >>> f = open('c:\python27\codes\greetings.txt','a')
3 >>> f.write(“\nPlease download the compiler from \n \t
'wwww.python.org'! ")
# check the file if it was properly written..
>>> f = open('c:\python27\codes\greetings.txt','r')
>>> print f.read()
Hey, welcome to my python class!
Please download the compiler from
'wwww.python.org'!
# append another line, open for reading and print contents
>>> f = open('c:\python27\codes\greetings.txt','a')
>>> f.write("\nNow lets start coding!")
>>> f = open('c:\python27\codes\greetings.txt','r')
>>> print f.read()
Hey, welcome to my python class!
Please download the compiler from
'wwww.python.org'!
Now lets start coding!

You might also like