CSC 201 Lecture Slides
CSC 201 Lecture Slides
CSC 201 Lecture Slides
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?
Text Editor
o Notepad, Notepad++, Sublime Text 2, EditPad 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
not NEGATION
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
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
- 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
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
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.
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
Syntax:
The general form of an if/else structure is:
if (expression):
<python statements1>
else:
<python statements2>
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:
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>
Syntax:
The general form of a while statement is:
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.
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 ;
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
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
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;
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
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.
Others include:
len(), chr(), min(), max(), range(), hex(), bin(), abs(), ord(), pow(),
raw_input(), sum(), format(), cmp(), dir(), oct(), round(), print()…etc.
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
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
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’ ;
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 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
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 ]
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.
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]
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;
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
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 )
Just like lists built-in functions such as max(), min(), len(), etc are
applicable to tuples
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}
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‘
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'}
200
300
400
100
>>> for product_id in products:
print "%d => %s " % (product_id,products[product_id])
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
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_.
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
-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.
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:
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
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
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
...
• 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
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
defined.
The iterator of a list is actually a listiterator object. A listiterator is its own iterator.
Object Oriented Python
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.
• 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
– 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
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
A class definition with multiple base classes looks like this in Python:
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
• 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
• 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
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.
Example
Notice the unfriendly error generated without the try…except block
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!"
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!"
LECTURE 13
A d va n c e d P y t h o n
Python Standard Libraries
Python Standard Library
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
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)
uniform (a, b) Return a random real number N such that a <= N < b.
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.
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
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
Output: C:\Python27\myPythonCodes
Alternatively:
import os
myPath = str(os.path.abspath('.'))
print (myPath)
Output: C:\Python27\myPythonCodes
Python Standard Library
Output: C:\Python27
Python Standard Library
Output: C:\Python27\myPythonCodes\control_structures
Output: C:\Python27
Python Standard Library
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
>>> import re
>>> myReg = re.search('(?<=-)\w+', 'Programming in-Python27')
>>> myReg.group(0)
'Python27'
Python Standard Library
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.
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
Number of students = 50
Sum = 3068
Average = 61
File Processing
Writing into Files
Writing into files in python can be performed as shown below;
>>> f.read()
'Hey, welcome to my python class!'