Python Programming Tutorial Part 1
Python Programming Tutorial Part 1
Python Programming Tutorial Part 1
For most of the examples given in this tutorial you will find Try it option, so just
make use of it and enjoy your learning.
#!/usr/bin/python
Chapter 1
Python - Overview
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer syntactical
constructions than other languages.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Python Features
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Portable − Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
Apart from the above-mentioned features, Python has a big list of good features,
few are listed below −
It provides very high-level dynamic data types and supports dynamic type
checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Chapter 2
Python - Environment Setup
Python is available on a wide variety of platforms including Linux and Mac OS X.
Let's understand how to set up our Python environment.
Open a terminal window and type "python" to find out if it is already installed and
which version is installed.
Win 9x/NT/2000
OS/2
PalmOS
Windows CE
Acorn/RISC OS
BeOS
Amiga
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
VMS/OpenVMS
QNX
VxWorks
Psion
Python has also been ported to the Java and .NET virtual machines
Installing Python
If the binary code for your platform is not available, you need a C compiler to
compile the source code manually. Compiling the source code offers more
flexibility in terms of choice of features that you require in your installation.
Follow the link to download zipped source code available for Unix/Linux.
make
make install
Windows Installation
Follow the link for the Windows installer python-XYZ.msi file where XYZ is
the version you need to install.
Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date.
See http://www.python.org/download/mac/ for instructions on getting the current
version along with extra tools to support development on the Mac. For older Mac
OS's before Mac OS X 10.3 (released in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation
at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete
installation details for Mac OS installation.
Setting up PATH
The path variable is named as PATH in Unix or Path in Windows (Unix is case
sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter
from any particular directory, you must add the Python directory to your path.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
To add the Python directory to the path for a particular session in Unix −
To add the Python directory to the path for a particular session in Windows −
1 PYTHONPATH
2 PYTHONSTARTUP
3 PYTHONCASEOK
4 PYTHONHOME
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Running Python
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a
command-line interpreter or shell window.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
1 -d
2 -O
3 -S
4 -v
5 -X
6 -c cmd
7 file
or
or
You can run Python from a Graphical User Interface (GUI) environment as well, if
you have a GUI application on your system that supports Python.
Macintosh − The Macintosh version of Python along with the IDLE IDE is
available from the main website, downloadable as either MacBinary or
BinHex'd files.
If you are not able to set up the environment properly, then you can take help
from your system admin. Make sure the Python environment is properly set up and
working perfectly fine.
Note − All the examples given in subsequent chapters are executed with Python
2.4.3 version available on CentOS flavor of Linux.
We already have set up Python Programming environment online, so that you can
execute all the available examples online at the same time when you are learning
theory. Feel free to modify any example and execute it online.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Chapter 3
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −
$ python
>>>
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Type the following text at the Python prompt and press the Enter −
If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!");. However in Python
version 2.4.3, this produces the following result −
Hello, Python!
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is
no longer active.
Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file −
We assume that you have Python interpreter set in PATH variable. Now, try to run
this program as follows −
$ python test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file
−
#!/usr/bin/python
We assume that you have Python interpreter available in /usr/bin directory. Now,
try to run this program as follows −
$./test.py
Hello, Python!
Python Identifiers
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Reserved Words
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.
Assert finally Or
Def if Return
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Elif in While
Else is With
Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example −
if True:
print "True"
else:
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
print "False"
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces
would form a block. The following example has various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure
you understood various blocks even if they are without braces.
#!/usr/bin/python
import sys
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
try:
except IOError:
sys.exit()
if file_text == file_finish:
file.close
break
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
file.write(file_text)
file.write("\n")
file.close()
if len(file_name) == 0:
sys.exit()
try:
except IOError:
sys.exit()
file_text = file.read()
file.close()
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
print file_text
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow
the use of the line continuation character (\) to denote that the line should
continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all
the following are legal −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
#!/usr/bin/python
# First comment
Hello, Python!
You can type a comment on the same line after a statement or expression −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
The following line of the program displays the prompt, the statement saying “Press
the enter key to exit”, and waits for the user to take action −
#!/usr/bin/python
Here, "\n\n" is 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.
The semicolon ( ; ) allows multiple statements on the single line given that neither
statement starts a new code block. Here is a sample snip using the semicolon −
Header lines begin the statement (with the keyword) and terminate with a colon (
: ) and are followed by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
suite
else :
suite
Many programs can be run to provide you with some basic information about how
they should be run. Python enables you to do this with -h −
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
[ etc. ]
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
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 4
Python - Variable Types
Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals or characters in these
variables.
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
a=b=c=1
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
respectively, and one string object with the value "john" is assigned to the variable
c.
The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
Numbers
String
List
Tuple
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Dictionary
Python Numbers
Number data types store numeric values. 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
long (long integers, they can also be represented in octal and hexadecimal)
Examples
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.
Python Strings
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
#!/usr/bin/python
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent,
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
lists are similar to arrays in C. One difference between them is that all the items
belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end
-1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
repetition operator. For example −
#!/usr/bin/python
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of
a number of values separated by commas. Unlike lists, however, tuples are
enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets (
[ ] ) and their elements and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-
only lists. For example −
#!/usr/bin/python
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −
#!/usr/bin/python
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays
or hashes found in Perl and consist of key-value pairs. A dictionary key can be
almost any Python type, but are usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example −
#!/usr/bin/python
dict = {}
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
1 int(x [,base])
2 long(x [,base] )
3 float(x)
4 complex(real [,imag])
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
5 str(x)
6 repr(x)
7 eval(str)
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Converts s to a set.
11 dict(d)
12 frozenset(s)
13 chr(x)
14 unichr(x)
15 ord(x)
16 hex(x)
17 oct(x)
Chapter 5
Types of Operator
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
[ Show Example ]
operand
These operators compare the values on either sides of them and decide the
relation among them. They are also called Relational operators.
[ Show Example ]
operator.
< If the value of left operand is less than the value of (a < b)
right operand, then condition becomes true. is true.
[ Show Example ]
Bitwise operator works on bits and performs bit by bit operation. Assume if a =
60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
<< Binary The left operands value is moved left by the a << 2 =
Left Shift number of bits specified by the right 240 (means
operand. 1111 0000)
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below −
equals id(y).
The following table lists all operators from highest precedence to lowest.
1 **
2 ~+-
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
3 * / % //
4 +-
5 >> <<
6 &
Bitwise 'AND'
7 ^|
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Chapter 6
Python - Decision Making
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
Following is the general form of a typical decision making structure found in most
of the programming languages −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
1 if statements
2 if...else statements
3 nested if statements
If the suite of an if clause consists only of a single line, it may go on the same line
as the header statement.
#!/usr/bin/python
var = 100
Chapter 7
Python - Loops
In general, statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on. There may be a situation
when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
1 while loop
2 for loop
3 nested loops
You can use one or more loop inside any another while, for or
do..while loop.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
Python supports the following control statements. Click the following links to check
their detail.
1 break statement
2 continue statement
3 pass statement
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Chapter 8
Python - Numbers
Number data types store numeric values. They are immutable data types, means
that changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. 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) − They are often called just integers or ints, are
positive or negative whole numbers with no decimal point.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
long (long integers ) − Also called longs, they are integers of unlimited
size, written like integers and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and
fractional parts. Floats may also be in scientific notation, 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). The real part of the number is a, and the imaginary part is b.
Complex numbers are not used much in Python programming.
Examples
Mathematical Functions
1 abs(x)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
2 ceil(x)
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
6 floor(x)
7 log(x)
8 log10(x)
9 max(x1, x2,...)
10 min(x1, x2,...)
11 modf(x)
12 pow(x, y)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
13 round(x [,n])
14 sqrt(x)
Random numbers are used for games, simulations, testing, security, and privacy
applications. Python includes following functions that are commonly used.
1 choice(seq)
3 random()
4 seed([x])
5 shuffle(lst)
6 uniform(x, y)
Trigonometric Functions
1 acos(x)
2 asin(x)
3 atan(x)
4 atan2(y, x)
5 cos(x)
6 hypot(x, y)
7 sin(x)
8 tan(x)
9 degrees(x)
10 radians(x)
Mathematical Constants
1 pi
2 e
Chapter 9
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 −
Python does not support a character type; these are treated as strings of length
one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring. For example −
#!/usr/bin/python
var1[0]: H
var2[1:5]: ytho
Updating Strings
#!/usr/bin/python
Escape Characters
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
\x Character x
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
[] Slice - Gives the character from the given index a[1] will
give e
[:] Range Slice - Gives the characters from the a[1:4] will
given range give ell
One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf()
family. Following is a simple example −
#!/usr/bin/python
Here is the list of complete set of symbols which can be used along with % −
Format Conversion
Symbol
%c Character
%o octal integer
Other supported symbols and functionality are listed in the following table −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Symbol Functionality
- left justification
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple
lines, including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double
quotes.
#!/usr/bin/python
"""
print para_str
When the above code is executed, it produces the 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) −
Raw strings do not treat the backslash as a special character at all. Every
character you put into a raw string stays the way you wrote it −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
print 'C:\\nowhere'
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression'as
follows −
#!/usr/bin/python
print r'C:\\nowhere'
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings
are stored as 16-bit Unicode. This allows for a more varied set of characters,
including special characters from most languages in the world. I'll restrict my
treatment of Unicode strings to the following −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix
r.
1 capitalize()
2 center(width, fillchar)
4 decode(encoding='UTF-8',errors='strict')
5 encode(encoding='UTF-8',errors='strict')
7 expandtabs(tabsize=8)
10 isalnum()
11 isalpha()
12 isdigit()
13 islower()
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
14 isnumeric()
15 isspace()
16 istitle()
17 isupper()
Returns true if string has at least one cased character and all
cased characters are in uppercase and false otherwise.
18 join(seq)
19 len(string)
20 ljust(width[, fillchar])
21 lower()
22 lstrip()
23 maketrans()
24 max(str)
25 min(str)
27 rfind(str, beg=0,end=len(string))
29 rjust(width,[, fillchar])
30 rstrip()
31 split(str="", num=string.count(str))
if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each
line with NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
34 strip([chars])
35 swapcase()
36 title()
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
37 translate(table, deletechars="")
38 upper()
39 zfill (width)
40 isdecimal()
Chapter 10
Python - Lists
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, slicing, adding, multiplying, and checking for membership. In
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
Python Lists
The list is a most versatile data type available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
#!/usr/bin/python
list2 = [1, 2, 3, 4, 5, 6, 7 ];
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with
the append() method. For example −
#!/usr/bin/python
print list[2]
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
list[2] = 2001;
print list[2]
To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For
example −
#!/usr/bin/python
print list1
del list1[2];
print list1
Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings
in the prior chapter.
Because lists are sequences, indexing and slicing work the same way for lists as
they do for strings.
1 cmp(list1, list2)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
Chapter 11
Python - Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
tup1 = ();
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 they can be sliced, concatenated,
and so on.
To access values in tuple, use the square brackets for slicing along with the index
or indices to obtain value available at that index. For example −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
tup2 = (1, 2, 3, 4, 5, 6, 7 );
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of
tuple elements. You are able to take portions of existing tuples to create new
tuples as the following example demonstrates −
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
# tup1[0] = 100;
print tup3
Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
print tup
del tup;
print tup
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple, not a
string.
Because tuples are sequences, indexing and slicing work the same way for tuples
as they do for strings. Assuming following input −
No Enclosing Delimiters
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
x, y = 1, 2;
1 cmp(tuple1, tuple2)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
2 len(tuple)
3 max(tuple)
4 min(tuple)
Chapter 12
Python - Dictionary
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: {}.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
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.
To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −
#!/usr/bin/python
dict['Name']: Zara
dict['Age']: 7
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
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying
an existing entry, or deleting an existing entry as shown below in the simple
example −
#!/usr/bin/python
dict['Age']: 8
dict['School']: DPS School
You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example –
#!/usr/bin/python
This produces the following result. Note that an exception is raised 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
Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the
keys.
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last assignment
wins. For example −
#!/usr/bin/python
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed. Following is a
simple example −
#!/usr/bin/python
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
3 str(dict)
4 type(variable)
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
5 dict.has_key(key)
6 dict.items()
7 dict.keys()
8 dict.setdefault(key, default=None)
9 dict.update(dict2)
10 dict.values()
Chapter 13
Python - Date & Time
A Python program can handle date and time in several ways. Converting between
date formats is a common chore for computers. Python's time and calendar
modules help track dates and times.
What is Tick?
There is a popular time module available in Python which provides functions for
working with times, and for converting between representations. The
function time.time() returns the current system time in ticks since 12:00am,
January 1, 1970(epoch).
Example
#!/usr/bin/python
ticks = time.time()
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
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.
What is TimeTuple?
1 Month 1 to 12
2 Day 1 to 31
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
3 Hour 0 to 23
4 Minute 0 to 59
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
To translate a time instant from a seconds since the epoch floating-point value into
a time-tuple, pass the floating-point value to a function (e.g., localtime) that
returns a time-tuple with all nine items valid.
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
This would produce the following result, which could be formatted in any other
presentable form −
You can format any time as per your requirement, but simple method to get time
in readable format is asctime() −
#!/usr/bin/python
import time;
The calendar module gives a wide range of methods to play with yearly and
monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) –
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print cal
There is a popular time module available in Python which provides functions for
working with times and for converting between representations. Here is the list of
all available methods −
1 time.altzone
2 time.asctime([tupletime])
Accepts a time-tuple and returns a readable 24-character
string such as 'Tue Dec 11 18:07:14 2008'.
3 time.clock( )
Returns the current CPU time as a floating-point number of
seconds. To measure computational costs of different
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
4 time.ctime([secs])
Like asctime(localtime(secs)) and without arguments is like
asctime( )
5 time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and
returns a time-tuple t with the UTC time. Note : t.tm_isdst is
always 0
6 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and
returns a time-tuple t with the local time (t.tm_isdst is 0 or 1,
depending on whether DST applies to instant secs by local
rules).
7 time.mktime(tupletime)
Accepts an instant expressed as a time-tuple in local time and
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
8 time.sleep(secs)
Suspends the calling thread for secs seconds.
9 time.strftime(fmt[,tupletime])
Accepts an instant expressed as a time-tuple in local time and
returns a string representing the instant as specified by string
fmt.
11 time.time( )
Returns the current time instant, a floating-point number of
seconds since the epoch.
12 time.tzset()
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
There are following two important attributes available with time module −
1 time.timezone
2 time.tzname
By default, calendar takes Monday as the first day of the week and Sunday as the
last one. To change this, call calendar.setfirstweekday() function.
1 calendar.calendar(year,w=2,l=1,c=6)
2 calendar.firstweekday( )
Returns the current setting for the weekday that starts each
week. By default, when calendar is first imported, this is 0,
meaning Monday.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
3 calendar.isleap(year)
4 calendar.leapdays(y1,y2)
5 calendar.month(year,month,w=2,l=1)
6 calendar.monthcalendar(year,month)
7 calendar.monthrange(year,month)
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Returns two integers. The first one is the code of the weekday
for the first day of the month month in year year; the second
one is the number of days in the month. Weekday codes are 0
(Monday) to 6 (Sunday); month numbers are 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
9 calendar.prmonth(year,month,w=2,l=1)
10 calendar.setfirstweekday(weekday)
11 calendar.timegm(tupletime)
12 calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes
are 0 (Monday) to 6 (Sunday); month numbers are 1 (January)
to 12 (December).
If you are interested, then here you would find a list of other important modules
and functions to play with date & time in Python −
Chapter 14
Python - Functions
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are called user-defined
functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
The code block within every function starts with a colon (:) and is indented.
Syntax
By default, parameters have a positional behavior and you need to inform them in
the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard
screen.
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt. Following is the example
to call printme() function −
#!/usr/bin/python
print str
return;
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
#!/usr/bin/python
mylist.append([1,2,3,4]);
return
mylist = [10,20,30];
changeme( mylist );
Here, we are maintaining reference of the passed object and appending values in
the same object. So, this would produce the following result −
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
#!/usr/bin/python
return
mylist = [10,20,30];
changeme( mylist );
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result −
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
To call the function printme(), you definitely need to pass one argument, otherwise
it gives a syntax error as follows −
#!/usr/bin/python
print str
return;
printme()
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters. You can also make keyword calls to the printme() function in the
following ways −
#!/usr/bin/python
print str
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
return;
My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
#!/usr/bin/python
return;
Name: miki
Age 50
Default arguments
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
return;
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-lengtharguments and
are not named in the function definition, unlike required and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. Following is a simple example −
#!/usr/bin/python
print arg1
print var
return;
printinfo( 10 )
Output is:
10
Output is:
70
60
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
50
These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword to
create small anonymous functions.
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.
Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
Syntax
#!/usr/bin/python
Value of total : 30
Value of total : 40
All the above examples are not returning any value. You can return a value from a
function as follows −
#!/usr/bin/python
return total;
Scope of Variables
All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python −
Global variables
Local variables
Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
This means that local variables can be accessed only inside the function in which
they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope. Following is a simple example −
#!/usr/bin/python
return total;
sum( 10, 20 );
Chapter 15
Python - Modules
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.
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, support.py
return
You can use any Python source file as a module by executing an import statement
in some other Python source file. The import has the following syntax −
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches before importing a module. For example, to import the
module support.py, you need to put the following command at the top of the script
−
#!/usr/bin/python
import support
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
support.print_func("Zara")
Hello : Zara
Python's from statement lets you import specific attributes from a module into the
current namespace. The from...import has the following syntax −
For example, to import the function fibonacci from the module fib, use the
following statement −
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.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
It is also possible to import all names from a module into the current namespace
by using the following import statement −
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the
following sequences −
If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the
function Money, we assign Money a value, therefore Python assumes Moneyas a
local variable. However, we accessed the value of the local variable Moneybefore
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# global Money
Money = Money + 1
print Money
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
AddMoney()
print Money
The dir() built-in function returns a sorted list of strings containing the names
defined by a module.
The list contains the names of all the modules, variables and functions that are
defined in a module. Following is a simple example −
#!/usr/bin/python
import math
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.
The globals() and locals() functions can be used to return the names in the global
and local namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.
When the module is imported into a script, the code in the top-level portion of a
module is executed only once.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module
again. The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do the
following −
reload(hello)
Packages in Python
Consider a file Pots.py available in Phone directory. This file has following line of
source code −
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
def Pots():
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 import statements in __init__.py as follows −
After you add these lines to __init__.py, you have all of these classes available
when you import the Phone package.
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
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.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Chapter 16
Python - Files I/O
This chapter covers all the basic I/O functions available in Python. For more
functions, please refer to standard Python documentation.
The simplest way to produce output is using the print statement where you can
pass zero or more expressions separated by commas. This function converts the
expressions you pass into a string and writes the result to standard output as
follows −
#!/usr/bin/python
Python provides two built-in functions to read a line of text from standard input,
which by default comes from the keyboard. These functions are −
raw_input
input
The raw_input([prompt]) function reads one line from standard input and returns
it as a string (removing the trailing newline).
#!/usr/bin/python
This prompts you to enter any string and it would display same string on the
screen. When I typed "Hello Python!", its output is like this −
#!/usr/bin/python
This would produce the following result against the entered input −
Until now, you have been reading and writing to the standard input and output.
Now, we will see how to use actual data files.
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to
call other support methods associated with it.
Syntax
1 r
Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed
at the beginning of the file.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
4 rb+
Opens a file for both reading and writing in binary format. The
file pointer placed at the beginning of the file.
5 w
Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
6 wb
Opens a file for writing only in binary format. Overwrites the file
if the file exists. If the file does not exist, creates a new file for
writing.
7 w+
8 wb+
9 a
Opens a file for appending. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
10 ab
11 a+
Opens a file for both appending and reading. The file pointer is
at the end of the file if the file exists. The file opens in the
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
append mode. If the file does not exist, it creates a new file for
reading and writing.
12 ab+
Once a file is opened and you have one file object, you can get various information
related to that file.
1 file.closed
2 file.mode
3 file.name
4 file.softspace
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
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.
Syntax
fileObject.close();
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.close()
The file object provides a set of access methods to make our lives easier. We
would see how to use read() and write() methods to read and write files.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string
−
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.close()
The above method would create foo.txt file and would write given content in that
file and finally it would close that file. If you would open this file, it would have
following content.
The read() method reads a string from an open file. It is important to note that
Python strings can have binary data. apart from text data.
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and if count is missing,
then it tries to read as much as possible, maybe until the end of file.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
fo.close()
File Positions
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.
If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2
then the end of the file would be taken as the reference position.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
position = fo.tell();
str = fo.read(10);
fo.close()
To use this module you need to import it first and then you can call any related
functions.
The rename() method takes two arguments, the current filename and the new
filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
You can use the remove() method to delete files by supplying the name of the file
to be deleted as the argument.
Syntax
os.remove(file_name)
Example
#!/usr/bin/python
import os
os.remove("text2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you create,
remove, and change directories.
You can use the mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method which contains
the name of the directory to be created.
Syntax
os.mkdir("newdir")
Example
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
import os
os.mkdir("test")
You can use the chdir() method to change the current directory. The chdir()
method takes an argument, which is the name of the directory that you want to
make the current directory.
Syntax
os.chdir("newdir")
Example
#!/usr/bin/python
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
import os
os.chdir("/home/newdir")
Syntax
os.getcwd()
Example
#!/usr/bin/python
import os
os.getcwd()
The rmdir() method deletes the directory, which is passed as an argument in the
method.
Syntax
os.rmdir('dirname')
Example
#!/usr/bin/python
import os
os.rmdir( "/tmp/test" )
There are three important sources, which provide a wide range of utility methods
to handle and manipulate files & directories on Windows and Unix operating
systems. They are as follows −
File Object Methods: The file object provides functions to manipulate files.
Chapter 17
1 Exception
2 StopIteration
3 SystemExit
4 StandardError
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
6 OverflowError
7 FloatingPointError
8 ZeroDivisionError
9 AssertionError
10 AttributeError
11 EOFError
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
12 ImportError
13 KeyboardInterrupt
14 LookupError
15 IndexError
16 KeyError
17 NameError
18 UnboundLocalError
19 EnvironmentError
Base class for all exceptions that occur outside the Python
environment.
20 IOError
21 IOError
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
22 SyntaxError
23 IndentationError
24 SystemError
25 SystemExit
26 TypeError
27 ValueError
Raised when the built-in function for a data type has the valid
type of arguments, but the arguments have invalid values
specified.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done
with your testing of the program.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid
input, and after a function call to check for valid output.
If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other
exception using the try-except statement, but if not handled, they will terminate
the program and produce a traceback.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Example
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
What is Exception?
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block. After the try: block,
include an except: statement, followed by a block of code which handles the
problem as elegantly as possible.
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the
else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's
protection.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Example
This example opens a file, writes content in the, file and comes out gracefully
because there is no problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
except IOError:
else:
fh.close()
Example
This example tries to open a file where you do not have write permission, so it
raises an exception −
#!/usr/bin/python
try:
fh = open("testfile", "r")
except IOError:
else:
You can also use the except statement with no exceptions defined as follows −
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using
this kind of try-except statement is not considered a good programming practice
though, because it catches all exceptions but does not make the programmer
identify the root cause of the problem that may occur.
You can also use the same except statement to handle multiple exceptions as
follows −
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
try:
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
......................
else:
You can use a finally: block along with a try: block. The finally block is a place to
put any code that must execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −
try:
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
......................
finally:
......................
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
finally:
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
If you do not have permission to open the file in writing mode, then this will
produce the following result −
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
finally:
fh.close()
except IOError:
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the exceptstatements if present in the
next higher layer of the try-except statement.
Argument of an Exception
try:
......................
If you write the code to handle a single exception, you can have a variable follow
the name of the exception in the except statement. If you are trapping multiple
exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of
a tuple. This tuple usually contains the error string, the error number, and an error
location.
Example
#!/usr/bin/python
def temp_convert(var):
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
try:
return int(var)
temp_convert("xyz");
Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.
Embedded Technosolutions
Venture of IIT Bombay & VJTI Alumni
Syntax
The final argument, traceback, is also optional (and rarely used in practice), and if
present, is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the
Python core raises are classes, with an argument that is an instance of the class.
Defining new exceptions is quite easy and can be done as follows −
if level < 1:
Note: In order to catch an exception, an "except" clause must refer to the same
exception thrown either class object or simple string. For example, to capture
above exception, we must write the except clause as follows −
try:
else:
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
except Networkerror,e:
print e.args