CSC 201 Lecture Slides
CSC 201 Lecture Slides
JOMO
FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE (FUTA)
Comparative Programming (CSC 202)
LECTURE 1
Introduction to Python Programming
Introduction: What is Python?
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
It is an open-source, general-purpose, and high level programming language with remarkable
power.
Highly compatible with many leading programming languages and frameworks such as Java, C/
C++, C#.NET etc.
Introduction: features of Python
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
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 following 203 int
basic types are supported. 4.03 float
- however complex types such as arrays, list, tupple,
“futa!" str
sets, dictionaries and user defined types are also
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 variable 2 >>> matno = “CSC/11/0036”
only when the variable is initialized. 3 >>> height = 4.5
4 >>> isGraduated = False
>>> score
60
- Python also supports scientific types
1 >>> comp = 4 + 3j
such as Complex Numbers and also 2 >>> print comp
provides means to carry out basic 3 (4+3j)
operations on them. E.g. Getting the 4 >>> comp.real
real, imaginary part or the conjugate of 5 4.0j
6 >>> comp.imag
the complex number.
7 3.0
8 >>> comp.conjugate()
9 (4-3j)
Python: Expressions & Operators
Python supports the following basic arithmetic operators;
not NEGATION
JOMO
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
Python I/O & Command-Line Interaction
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 str() 1 >>> name = "Wole"
2 >>> age = 56
on line:12 is used to convert 3 >>> print name
the integer variable age to a 4 Wole
5 >>> print name,age
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
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/.
Enter the name of any module, keyword, or topic to get help on writing Python programs and using
4 Python modules. To quit this help utility and return to the interpreter, just type "quit".
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".
5
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 ********************
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
JOMO
| 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__(...)
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‘]
>>> dir(age)
2 ['__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:
Examples of repetition structures are:
while
for
JOMO
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
Control Structures: Repetition
The range() function
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, 120, 122, 124, 126, 128]
13 >>> range(100,130,5)
14 [100, 105, 110, 115, 120, 125]
15 >>> range(130,100,-5)
16 [130, 125, 120, 115, 110, 105]
17
Control Structures: Repetition
Examples :
Lets us look at how the range() function is use within a for block ;
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.
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
Defining Python Functions & 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
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.
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.
Others include:
len(), chr(), min(), max(), range(), hex(), bin(), abs(), ord(), pow(), raw_input(), sum(),
format(), cmp(), dir(), oct(), round(), print()…etc.
Python Functions and Procedures
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 while 3 val = (X + inc)
inc and val are all local to function 4 return val
5 print increment(50)
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 = ' "+ str(version)
10 >>> load_newest_app()
11 version in 'load_newest_app = ' 2.72
12 >>> print "current version is still "+ str(version)
13 current version is still 2.72
Comparative Programming (CSC 202)
LECTURE 5
Strings, Strings and Pattern Matching
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
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
\t Tab 7 >>> text = "The clerk said \"Come back
tomorrow!\" "
\r Carriage return
8 >>> print text
9 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 second line,\n Here is the last line"
2 >>> print text
3 This is the first line,
4 Followed by the second line,
5 Here is the last line
6 >>> text = "Matric\tTest1\tTest2\tExam\tTotal"
7 >>> print text
8 MatricTest1 Test2 Exam Total
9 >>> text = "Matric\tTest1\tTest2\tExam\tTotal\n======================================"
10 >>> print text
MatricTest1 Test2 Exam Total
=====================================
11
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."""
>>> print text
These are collection of characters that are used to store
and represent textual information.
2 They can be used to store anything data that will include letters or
3 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 " + "Engineering"
10 >>> print eee
11 Electrical & Electronics Engineering
Processing String Data
Basic String Operations
String Iteration: using loops to enumerate the characters of a string one after the other.
X[ k : n : m], all characters from index k to index n-1 at step m, when k < n, m is
Processing String Data
For example:
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 biros----"
2 >>> s.capitalize()
3 '---a biro is a pen, but not all pens are biros----'
4 >>> s.count('biro')
5 2
6 >>> s.find('pens')
7 32
8 >>> s.index('pens')
9 32
10 >>> s.index('biros')
11 41
12 >>> s.endswith('biros')
13 False
14 >>> ','.join(["SOS","SAAT","SET","SMES","SEET","SMAT"])
15 'SOS,SAAT,SET,SMES,SEET,SMAT'
16
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.
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
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
Score[0] 87
Score[3] 99
Score[2] 35
Score[3] 99
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 ], 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
1 k>>>
is +ve, when > nScore
then =m[56,87,35,99]
must be –ve.
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.
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.
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
Tuples, and Dictionaries
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
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])
8
Dictionary Structure: Operations
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_.
Grouping related code into a module makes the code easier to understand and
use.
Error containment i.e. it confines program error (s) to a section of the code.
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.
-Example: Write a Python program to import and use the greeting.py module defined
above.
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:
def determine_the_nature(a, b, c) :
disc = b * b - 4 * a * c
if (disc == 0):
return 0
elif (disc > 0):
return 1
else:
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
- Simply put, importing from different directories implies importing from different
packages.
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
Classes, Properties, and Methods
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
inFib’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
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
Object-Oriented Python II
Access specifiers, Iterators, Generators
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
• Iterator - An iterator is an object that supports the iterator protocol which basically means
It has anext method defined (__next__ in Python 3.x) which returns the next
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.
②
“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 forloop 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
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 returninstead.
Object Oriented Python
• A generator function is an ordinary function object in all respects, but has the new
• 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.
• NB: When the intent is clear from context, the unqualified name "generator" may be used to
• Each time the .next() method of a generator-iterator is invoked, the code in the body of the
• If a yield statement is encountered, the state of the function is frozen, and the value of
• 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
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):
...
– Each time next() is called, the generator resumes where it left-off (it remembers all the
LECTURE 11
Object-Oriented Python III
Inheritance and Method Overloading
Object Oriented Python
INHERITANCE
• The subclasses can override the logic in a superclass, allowing you to change
• 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 functionissubclass() 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
• 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
• 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
Advanced Python
Handling Errors & Exceptions
Handling Errors & Exception
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.
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? "))
area = 3.142 * radius * radius
3 print area
4 except:
5 print "Radius must be numeric!"
6
Example
1 >>> try:
2 radius = float(raw_input("What is the radius of the Circle? "))
area = 3.142 * radius * radius
3 print area
4 except:
5 print "Radius must be numeric!"
6
LECTURE 13
Advanced Python
Python Standard Libraries
Python Standard Library
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
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.
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
You are expected to predict correctly at least three numbers in the outcome to
be qualified for any benefits.
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)
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
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)
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
Parameter Description
pattern This is the regular expression to be matched.
This is the string which would be searched to match the
string
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.
>>> import re
>>> myReg = re.search('(?<=-)\w+', 'Programming in-Python27')
>>> myReg.group(0)
'Python27'
Python Standard Library
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
Comparative Programming (CSC 202)
LECTURE 14
Advanced Python
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
>>> 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\file2.txt','r')
2 # read the first 8 bytes i.e. characters
3 >>> 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;
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!")
>>> f.read()
'Hey, welcome to my python class!'