Professional Documents
Culture Documents
Rajan T K
Department of Mathematics
Govt Victoria College, Palakkad
Chapter 1
Introduction
Python is a high-level, interpreted, interactive and object oriented-scripting language.Python was
designed to be highly readable which uses English keywords frequently where as other languages
use punctuation and it has fewer syntactical constructions than other languages.
The language was developed by Guido van Rossum in the late eighties and early nineties at the Na-
tional Research Institute for Mathematics and Computer Science in the Netherlands.
1. 2 Python Features
Python's feature highlights include:
• Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language in a relatively short period of time.
• Easy-to-read: Python code is much more clearly defined and visible to the eyes.
• Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain.
• A broad standard library: One of Python's greatest strengths is the bulk of the library is
very portable and cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Support for an interactive mode in which you can enter results from a
terminal right to the language, allowing interactive testing and debugging of snippets of
code.
• Portable: Python can run on a wide variety of hardware platforms and has the same inter-
face on all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These modules en-
able programmers to add to or customize their tools to be more efficient.
• Databases: Python provides interfaces to all major commercial databases.
• GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
• Scalable: Python provides a better structure and support for large programs than shell
scripting.
Chapter 2
Python - Basic Syntax
2.1 First Python Program
2.1.1 Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
$ python
Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more info.
Type the following text to the right of the Python prompt and press the Enter key:
>>> print "Hello, Python!"
Here I assumed that you have Python interpreter available in /usr/bin directory. Now try to run this
program as follows:
$ chmod +x test.py # This is to make file executable
$ python test.py
You have seen a simple Python program in interactive as well as script mode, now lets see few ba-
sic concepts related to Python Syntax:
• Class names start with an uppercase letter and all other identifiers with a lowercase letter.
• Starting an identifier with a single leading underscore indicates by convention that the iden-
tifier is meant to be private.
• Starting an identifier with two leading underscores indicates a strongly private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
Thus, in Python all the continuous lines indented with similar number of spaces would form a
block. Following is the example having various statement blocks:
Note: Don't try to understand logic or different functions used. Just make sure you understood vari-
ous blocks even if they are without braces.
#!/usr/bin/python
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text
Statements contained within the [], {}, or () brackets do not need to use the line continuation char-
acter. For example:
days = ['Monday', 'Tuesday',
'Wednesday',
'Thursday', 'Friday']
# First comment
print "Hello, Python!"; # second comment
Here "\n\n" are being used to create two new lines before displaying the actual line.
Once the user presses the key, the program ends. This is a nice trick to keep a console window open
until the user is done with an application.
Example:
if
expression
:
suite
elif
expression
:
suite
else :
suite
You can also program your script in such a way that it should accept various options. Command
line arguments is an advanced topic and should be studied a bit later once you have gone through
rest of the Python concepts.
Chapter 3
>>>print counter
>>>print miles
>>>print name
Here 100, 1000.0 and "John" are the values assigned to counter, miles and name variables, respec-
tively. While running this program, this will produce following result:
100
1000.0
John
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables. For example:
>>>a, b, c = 1, 2,
"john"
Here two integer objects with values 1 and 2 are assigned to variables a and b, and one string object
with the value "john" is assigned to the variable c.
• Numbers
• String
• List
• Tuple
• Set
• Dictionary
You can also delete the reference to a number object by using the del statement. The syntax of the
del statement is:
>>> del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
>>> del var
>>> del var_a, var_b
Examples:
Here are some examples of numbers:
intlong float complex
1051924361L 0.0 3.14j
100-0x19323L 15.20 45.j
-7860122L -21.9 9.322e-36j
0800xDEFABCECBDAEC 32.3+e18 .876j
BFBAEl
-0490535633629843L -90. -.6545+0J
-0x260-052318172735L -32.54e100 3e+26J
0x69-4721885298529L 70.2-E12 4.53e-7j
• Python allows you to use a lowercase L with long, but it is recommended that you use only
an uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
• A complex number consists of an ordered pair of real floatingpoint numbers denoted by a +
bj, where a is the real part and b is the imaginary part of the complex number.
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
Following is invalid with tuple, because we attempted to update a tuple,which is not allowed. Simi-
lar case is possible with lists:
#!/usr/bin/python
Example:
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
x = {'name': 'john','code':6734,
'dept': 'sales'}
• Arithmetic Operators
• Comparision Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Control Statements
Normally a program runs executing the instructions line by line. But there are cases where we want
to skip or repeat a set of statements based on certain conditions. This is realized by using special
statements called control statement. With the control statement the flow of execution in the program
can be controlled. Here we discuss such statements.
5.1 Branching
Conditional constructs are used to incorporate decision making into programs. The result of this de-
cision making determines the sequence in which a program will execute instructions. You can con-
trol the flow of a program by using conditional constructs.
Here if statement, condition is evaluated first. If condition is true that is, if its value is nonzero then
the statement(s) block are executed. Otherwise, the next statement following the statement(s) block
is executed.
Note: In Python, all the statements indented by the same number of character spaces after a pro-
gramming construct are considered to be part of a single block of code. Python uses indentation as
its method of grouping statements.
Example:
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
statement(s)Example:
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
Note: Python does not currently support switch or case statements as in other languages.
Example:
#!/usr/bin/python
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var2
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
Example:
#!/usr/bin/python
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
Example:
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
The block here, consisting of the print and increment statements, is executed repeatedly until count
is no longer less than 9. With each iteration, the current value of the index count is displayed and
then increased by 1.
Example:
Following loop will continue till you enter 1 at command prompt:
#!/usr/bin/python
var = 1
while var == 1 : # This constructs an infinite
loop
num = raw_input("Enter a number :")
print "You entered: ", num
Above example will go in an infite loop and you would need to use CNTL+C to come out of the
program.
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in
the list is assigned to iterating_var, and the statements(s) block is executed until the entire sequence
is exhausted.
Note: In Python, all the statements indented by the same number of character spaces after a pro-
gramming construct are considered to be part of a single block of code. Python uses indentation as
its method of grouping statements.
Example:
#!/usr/bin/python
for letter in 'Python': # First
Example
print 'Current Letter :', letter
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
var = 10 # Second
Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
Example:
#!/usr/bin/python
var = 10 # Second
Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
continue
Example:
#!/usr/bin/python
The preceding code does not execute any statement or code if the value of letter is 'h'. The pass
statement is helpful when you have created a code block but it is no longer required.
You can then remove the statements inside the block but let the block remain with a pass statement
so that it doesn't interfere with other parts of the code.
• If the else statement is used with a for loop, the else statement is executed when the loop has
exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is executed when the con-
dition becomes false.
Example:
The following example illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
#!/usr/bin/python
Similar way you can use else statement with while loop.
Chapter 6
Python – Numbers
6.1 Introduction
Number data types store numeric values. They are immutable data types, which means that chang-
ing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the
del statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
del var
del var_a, var_b
• int (signed integers): often called just integers or ints, are positive or negative whole num-
bers with no decimal point.
• long (long integers ): or longs, are integers of unlimited size, written like integers and fol-
lowed by an uppercase or lowercase L.
• float (floating point real values) : or floats, represent real numbers and are written with a
decimal point dividing the integer and fractional parts. Floats may also be in scientific nota-
tion, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
• complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of .1 (which is an imaginary number). a is the real part of the
number, and b is the imaginary part. Complex numbers are not used much in Python pro-
gramming.
Examples:
Here are some examples of numbers:
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
0xDEFABCECBDAE
080 32.3+e18 .876j
CBFBAEl
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
• Python allows you to use a lowercase L with long, but it is recommended that you use only
an uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
• A complex number consists of an ordered pair of real floatingpoint numbers denoted by a +
bj, where a is the real part and b is the imaginary part of the complex number.
Python – Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming"
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
Here is the list of complete set of symbols which can be used along with %:
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Other supported symbols and functionality are listed in the following table:
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
add the octal leading zero ( '0' ) or hexadecimal leading '0x' or
#
'0X', depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m is the minimum total width and n is the number of digits to
m.n.
display after the decimal point (if appl.)
This will produce following result. Note how every single special character has been converted to
its printed form, right down to the last NEWLINE at the end of the string between the "up." and
closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the
end of a line or its escape code (\n):
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
print 'C:\\nowhere'
Mow let's make use of raw string. We would put expression in r'expression' as follows:
#!/usr/bin/python
print r'C:\\nowhere'
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Python - Lists
8.1 Python Sequences:
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a
number - its position, or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples which we
would see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing, slic-
ing, adding, multiplying, and checking for membership. In addition, Python has built-in functions
for finding the length of a sequence, and for finding its largest and smallest elements.
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Example:
#!/usr/bin/python
When looping through a sequence, the position index and corresponding value can be retrieved at
the same time
using the enumerate() function.
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
Python – Tuples
9.1 Introduction
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only
difference is that tuples can't be changed ie. tuples are immutable and tuples use parentheses and
lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values and optionally you can
put these comma-separated values between parentheses also. For example:
tup1 = ('physics', 'chemistry', 1997,
2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
To write a tuple containing a single value you have to include a comma, even though there is only
one value:
tup1 = (50,);
Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.
Example:
#!/usr/bin/python
Example:
#!/usr/bin/python
print tup;
del tup;
print "After deleting tup : "
print tup;
This will produce following result. Note an exception raised, this is because after del tup tuple does
not exist any more:
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Python – Dictionary
10.1 Introduction
A dictionary is mutable and is another container type that can store any number of Python objects,
including other container types.
Dictionaries consist of pairs (called items) of keys and their corresponding values.
Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dic-
tionary is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty dictionary without any items is written with just
two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of
any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Example:
#!/usr/bin/python
If we attempt to access a data item with a key which is not part of the dictionary, we get an error as
follows:
#!/usr/bin/python
When looping through dictionaries, the key and corresponding value can be retrieved at the same
time using the
iteritems() method.
Example:
#!/usr/bin/python
This will produce following result. Note an exception raised, this is because after del dict dictionary
does not exist any more:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ",
dict['Age'];
TypeError: 'type' object is
unsubscriptable
Example 1:
#!/usr/bin/python
(b) Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary
keys but something like ['key'] is not allowed.
Example 2:
#!/usr/bin/python
Example:
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:",
ticks
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in
this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime
in 2038 for UNIX and Windows.
localtime =
time.localtime(time.time())
print "Local current time :",
localtime
This would produce following result which could be formatted in any other presentable form:
Local current time : (2008, 5, 15, 12, 55, 32, 0, 136, 1)
cal = calendar.month(2008,
1)
print "Here is the
calendar:"
print cal;
Example:
# Filename: function1.py
def sayHello():
print('Hello World!') # block belonging to the function
# End of function
Example:
# Filename: func_return.py
The maximum function returns the maximum of the parameters, in this case the numbers supplied
to the function. It uses a simple if..else statement to find the greater value and then returns that
value. Note that a return statement without a value is equivalent to return None. Every function
implicitly contains a return None statement at the end unless you have written your own return
statement.
The pass statement is used in Python to indicate an empty block of statements. It returns nothing.
This is commonly used for creating minimal classes:
Example:
# Filename: break.py
while True:
s = (input('Enter something : '))
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Example:
# Filename: continue.py
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
# Filename: func_param.py
Example:
# Filename: func_local.py
x = 50
def fun(x):
print('x is', x)
x = 2
print('Changed local x to', x)
fun(x)
print('x is still', x)
# Filename: func_global.py
x = 50
def fun():
global x
print('x is', x)
x +=3
print('Changed global x to', x)
fun()
print('Value of x is', x)
The global statement is used to declare that x is a global variable - hence, when we assign a value to
x inside the function, that change is reflected when we use the value of x in the main block. You can
specify more than one global variable using the same global statement. For example, global x, y, z.
Example:
def prod(a,b=1,c=1):
return a*b*c
Care should be taken that if there are nondefault arguments also in the function they should come
first in the list of arguments. In a program def func(a, b=5) is valid, but def func(a=5, b) is not valid.
12.10 DocStrings
Python has a nifty feature called documentation strings, usually referred to by its shorter name
docstrings. DocStrings are an important tool that you should make use of since it helps to document
the program better and makes it easier to understand. Amazingly, we can even get the docstring
back from, say a function, when the program is actually running!
Example:
# filename : maxim.py
def mx(x,y):
' ' ' Function that returns maximum of two numbers
Syntax : mx(x,y)
Example : mx(32,56) ' ' '
if x > y:
return x
else:
return y
Doc string is typed within triple quotes. Information like help can be given in this manner. When
help(maxim) is typed in interactive mode the doc string will be displayed. Doc string is strongly
recommended in modules.
• Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expres-
sion.
• Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not equiva-
lent to inline statements in C or C++, whose purpose is by passing function stack allocation
during invocation for performance reasons.
Syntax:
The syntax of lambda functions contains only a single statement, which is as follows:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
Following is the example to show how lambda form of function works:
#!/usr/bin/python
Python – Modules
13.1 Introduction
A module allows you to logically organize your Python code. Grouping related code into a module
makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes, and
variables. A module can also include runnable code.
Example:
The Python code for a module named aname normally resides in a file named aname.py. Here's an
example of a simple module, hello.py
def print_func( par ):
print "Hello : ", par
return
When the interpreter encounters an import statement, it imports the module if the module is present
in the search path. Asearch path is a list of directories that the interpreter searches before importing
a module.
Example:
To import the module hello.py, you need to put the following command at the top of the script:
#!/usr/bin/python
A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening over and over again if multiple imports occur.
13.3 The from...import Statement
Python's from statement lets you import specific attributes from a module into the current names-
pace:
Syntax:
from modname import name1[, name2[, ... nameN]]
Example:
For example, to import the function fibonacci from the module fib, use the following statement:
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces
the item fibonacci from the module fib into the global symbol table of the importing module.
This provides an easy way to import all the items from a module into the current namespace; how-
ever, this statement should be used sparingly.
The module search path is stored in the system module sys as the sys.path variable. The sys.path
variable contains the current directory, PYTHONPATH, and the installation-dependent default.
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
Example:
#!/usr/bin/python
content = dir(math)
print content;
Here the special string variable __name__ is the module's name, and __file__ is the filename from
which the module was loaded.
Example:
Consider a file Pots.py available in Phone directory. This file has following line of source code:
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way we have another two files having different functions with the same name as above:
• Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit im-
port statements in __init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you've added these lines to __init__.py, you have all of these classes available when you've
imported the Phone package:
#!/usr/bin/python
Phone.Pots()
Phone.Isdn()
Phone.G3()
Note: In the above example, we have taken example of a single functions in each file, but you can
keep multiple functions in your files. You can also define different Python classes in those files and
then you can create your packages out of those classes.
Chapter 14
• file_name: The file_name argument is a string value that contains the name of the file that
you want to access.
• access_mode: The access_mode determines the mode in which the file has to be opened ie.
read, write append etc. A complete list of possible values is given below in the table. This is
optional parameter and the default file access mode is read (r)
• buffering: If the buffering value is set to 0, no buffering will take place. If the buffering
value is 1, line buffering will be performed while accessing a file. If you specify the buffer-
ing value as an integer greater than 1, then buffering action will be performed with the indi-
cated buffer size. This is optional paramter.
Modes Description
Opens a file for reading only. The file pointer is placed at the beginning of the file.
r
This is the default mode.
Opens a file for reading only in binary format. The file pointer is placed at the
rb
beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer will be at the beginning
r+
of the file.
Opens a file for both reading and writing in binary format. The file pointer will be
rb+
at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the file does
w
not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the file exists.
wb
If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if the file
w+
exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for both writing and reading in binary format. Overwrites the existing
wb+ file if the file exists. If the file does not exist, creates a new file for reading and
writing.
Opens a file for appending. The file pointer is at the end of the file if the file
a exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.
Opens a file for appending in binary format. The file pointer is at the end of the
ab file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
Opens a file for both appending and reading. The file pointer is at the end of the
a+ file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Opens a file for both appending and reading in binary format. The file pointer is at
ab+ the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
One can open and use files for reading or writing by creating an object of the file class. A file is
opened by using open() command in the form f=open(filename, mode). The first argument is a
string containing the filename. The second argument is another string containing a few characters
describing the way in which the file will be used. mode can be ’r’ when the file will only be read,
’w’ for only writing (an existing file with the same name will be erased), and ’a’ opens the file for
appending; any data written to the file is automatically added to the end. ’r+’ opens the file for both
reading and writing. The 'b' mode is to open a binary file and 't' mode is to open a text file. The
mode argument is optional; ’r’ will be assumed if it’s omitted.
read(), readline() and write() are methods of file object. To read a file’s contents, call
f.read(size), where size indicates the no of bytes to be read and it is optional. If the end of the file
has been reached, f.read() will return an empty string (""). f.readline() reads a single line from the
file. f.readlines() returns a list containing all the lines of data in the file. f.write(string) writes the
contents of string to the file, returning None. f.tell() returns an integer giving the file object’s
current position in the file. f.seek() method is to change the position. f.close() method is to close
the file f and free up any system resources taken up by the open file. After calling f.close(), attempts
to use the file object will automatically fail.
The close() method of a file object flushes any unwritten information and closes the file object, after
which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It
is a good practice to use the close() method to close a file.
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
import pickle
x=range(10)
f=open(numberlist, 'wb')
pickle.dump(x,f)
f.close()
f=open(numberlist,'rb')
y= pickle.load(f)
print y
You can use the chdir() method to change the current directory. The chdir() method takes an argu-
ment, which is the name of the directory that you want to make the current directory.
#!/usr/bin/python
import os
The rmdir() method deletes the directory, which is passed as an argument in the method. Before re-
moving a directory, all the contents in it should be removed.
#!/usr/bin/python
import os
15.2 Classes
In all the programs we wrote till now, we have designed our program around functions i.e.
blocks of statements which manipulate data. This is called the procedure-oriented way of
programming. There is another way of organizing your program which is to combine data and
functionality and wrap it inside something called an object. This is called the object oriented
programming.Classes and objects are the two main aspects of object oriented programming. A class
creates a new type where objects are instances of the class. Objects can store data using ordinary
variables that belong to the object. Variables that belong to an object or class are referred to as
fields. Objects can also have functionality by using functions that belong to a class. Such functions
are called methods of the class. Collectively, the fields and methods can be referred to as the
attributes of that class. Fields are of two types - they can belong to each instance/object of the class
or they can belong to the class itself. They are called instance variables and class variables
respectively.
Here class student is created. It has a method 'sayhi'. Now create an object of this class
p=student()
p.sayhi()
p is an object of type student. p.sayhi() will display 'hello how are you'. Here we see the self in
action. Notice that the sayhi method takes no parameters but still has the self in the function
definition.
There are many significant methods in python classes. One of them is __init__ method. The
__init__ method is run as soon as an object of a class is instantiated. The method is useful for
initialising an object.
Example:
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, sname):
self.name = sname
def sayHi(self):
print('Hello, my name is', self.name)
p = Person('Swaroop')
p.sayHi()
The __init__ method as taking a parameter name (along with the usual self). It
passes the arguments in the parentheses following the class name when creating a new instance of
the class. This is the special significance of this method. We are able to use the self.name field in
our methods which is demonstrated in the sayHi method.
Class student:
strength=0
def __init__(self, sname):
self.name=sname
print ' Initialising %s ' %(self.name)
student.strength +=1
def remove(self):
print 'Removing %s from the roll' %(self.name)
student.strength =1
if student.strength==0:
print 'there are still %d students in the roll'%
(student.strength)
else:
print ' %s is the last student in the roll' %(self.name)
def size():
print ' Now the student strength is %d' %(student.strength)
size=staticmethod(size)
p=student('Sunil T P')
q=student('Rajan T K')
r=student('Jalaja M')
student.size()
In this example student is the class name. p,q and r are objects, instances of the class. strength
belongs to student class and hence is a class variable. The variable sname belongs to an object and
hence is an object variable. The size is actually a method that belongs to the class and not to the
object and here it is static method. There is a special method remove() for removing an object
created. To remove the object p type p.remove()
15.5 Inhertitance
One of the major benefits of object oriented programming is reuse of code and one of the
ways to achieve this is through the inheritance mechanism.
Inheritance can be best imagined as implementing a type and subtype relationship between classes.
Suppose you want to write a program which has to keep track of the teachers and students in
a college. They have some common characteristics such as name, age and address. They also have
specific characteristics such as salary, courses and leaves for teachers and, marks and fees for
students. You can create two independent classes for each type and process them but adding a new
common characteristic would mean adding to both of these independent classes. This quickly
becomes unwieldy. A better way would be to create a common class called SchoolMember and then
have the teacher and student classes inherit from this class i.e. they will become sub-types of this
type (class) and then we can add specific characteristics to these sub-types. There are many
advantages to this approach. If we add/change any functionality in SchoolMember, this is
automatically reflected in the subtypes as well. For example, you can add a new ID card field for
both teachers and students by simply adding it to the SchoolMember class. However, changes in the
subtypes do not affect other subtypes. Another advantage is that if you can refer to a teacher or
student object as a SchoolMember object which could be useful in some situations such as counting
of the number of school members. This is called polymorphism where a sub-type can be
substituted in any situation where a parent type is expected i.e. the object can be treated as an
instance of the parent class. Also observe that we reuse the code of the parent class and we do not
need to repeat it in the different classes as we would have had to in case we had used independent
classes. The SchoolMember class in this situation is known as the base class or the superclass. The
Teacher and Student classes are called the derived classes or subclasses. Let us see the following
example.
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print (Initialized SchoolMember: {0})'.format(self.name)
def tell(self):
'''Tell my details.'''
print 'Name:"{0}" Age:"{1}"'.format(self.name, self.age)
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: {0})'.format(self.name)
def tell(self):
SchoolMember.tell(self)
print 'Salary: "{0:d}"'.format(self.salary)
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: {0})'.format(self.name)
def tell(self):
SchoolMember.tell(self)
print 'Marks: "{0:d}"'.format(self.marks)
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
Chapter 16
The error in the use of python language is syntax error. Even if a statement or expression is
syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected
during execution are called exceptions . ZeroDivisionError, TypeError, NameError etc. are certain
type of exceptions. Where as the symantic error is the error in the ouput, even if the program is
without synatx error and exception.
try:
text = input('Enter something --> ')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {0}'.format(text))
Note that there has to be at least one except clause associated with every try clause. Otherwise,
what's the point of having a try block? If any error or exception is not handled, then the default
Python handler is called which just stops the execution of the program and prints an error message.
We have already seen this in action above. One can also have an else clause associated with a try-
except block. The else clause is executed if no exception occurs.
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
# Other work can continue as usual here
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except ShortInputException as ex:
print('ShortInputException: The input was {0} long, expected at
least {1}'.format(ex.length, ex.atleast))
else:
print('No exception was raised.')
import time
try:
f = open('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
print(line)
time.sleep(2) # To make sure it runs for a while
except KeyboardInterrupt:
print('!! You cancelled the reading from the file.')
finally:
f.close()
print('(Cleaning up: Closed the file)')
A finally clause is always executed before leaving the try statement, whether an exception has
occurred or not.
The finally clause is executed in any event. The TypeError raised by dividing two strings is not
handled by the except clause and therefore re-raised after the finally clause has been executed.
Chapter 17
’C:>Python26’
>>> os.chdir(’/server/accesslogs’)
The builtin dir() and help() functions are useful as interactive aids for working with large
modules like os.
>>> import os
>>> dir(os)
>>> help(os)
For daily file and directory management tasks, the shutil module provides a higher level interface
that is easier
to use:
The glob module provides a function for making file lists from directory wildcard searches.
>>> glob.glob(’*.py’)
[’primes.py’, ’random.py’, ’quote.py’]
The math module gives access to the underlying C library functions for floating point math.
>>> import math
0.70710678118654757
>>> math.log(1024, 2)
10.0
’apple’
0.17970987693706186
There are a number of modules for accessing the internet and processing internet protocols. Two of
the simplest are urllib2 for retrieving data from urls and smtplib for sending mail.
Example 1
>>>import urllib2
>>>response = urllib2.urlopen(’http://python.org/’)
>>>html = response.read()
Example 2
>>> import urllib2
>>>for line in urllib2.urlopen(’http://www.tycho.usno.navy.mil /
cgi-bin / timer.pl’):
>>>server.sendmail(’soothsayer@example.org’, jcaesar@example.org’,
...
... """)
>>> server.quit()
The datetime module supplies classes for manipulating dates and times in both simple and complex
ways.
# dates are easily constructed and formatted
>>> now
datetime.date(2003, 12, 2)
>>> age.days
14368
Output Formatting:
The repr module provides a version of repr() customized for abbreviated displays of large or
deeply nested containers.
>>> import repr
>>> repr.repr(set(’supercalifragilisticexpialidocious’))
The pprint module offers more sophisticated control over printing both built-in and user defined
objects in a
way that is readable by the interpreter. When the result is longer than one line, the “pretty printer”
adds line breaks
and indentation to more clearly reveal data structure.
...
[[[[’black’, ’cyan’],
’white’,
[’green’, ’red’]],
[[’magenta’, ’yellow’],
’blue’]]]
The textwrap module formats paragraphs of text to fit a given screen width.
>>> doc = """The wrap() method is just like fill() except that it
returns
... a list of strings instead of one big string with newlines to
separate
... the wrapped lines."""
...
The locale module accesses a database of culture specific data formats. The grouping attribute of
locale’s format function provides a direct way of formatting numbers with group separators:
>>> x = 1234567.8
’1,234,567’
’$1,234,567.80’
The string module includes a versatile Template class with a simplified syntax suitable for editing
by end users. This allows users to customize their applications without having to alter the
application. The format uses placeholder names formed by $ with valid Python identifiers in brace
brackets.
The decimal module offers a Decimal datatype for decimal floating point arithmetic.
Decimal("0.7350")
0.73499999999999999