Python Tutorial
Python Tutorial
Characteristics of Python
Following are important characteristics of Python Programming −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Applications of Python
As mentioned before, Python is one of the most widely used language over the web.
I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable 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.
Audience
This Python tutorial is designed for software programmers who need to learn Python
programming language from scratch.
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A
basic understanding of any of the programming languages is a plus.
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.
Python is Interpreted − Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it. This is similar to PERL
and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
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 is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable 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.
Apart from the above-mentioned features, Python has a big list of good features, few
are listed below −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
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 is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable 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.
Apart from the above-mentioned features, Python has a big list of good features, few
are listed below −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python https://www.python.org/
You can download Python documentation from https://www.python.org/doc/. The
documentation is available in HTML, PDF, and PostScript formats.
Installing Python
Python distribution is available for a wide variety of platforms. You need to download
only the binary code applicable for your platform and install 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.
Here is a quick overview of installing Python on various platforms −
Unix and Linux Installation
Here are the simple steps to install Python on Unix/Linux machine.
Open a Web browser and go to https://www.python.org/downloads/.
Follow the link to download zipped source code available for Unix/Linux.
Download and extract files.
Editing the Modules/Setup file if you want to customize some options.
run ./configure script
make
make install
This installs Python at standard location /usr/local/bin and its libraries
at /usr/local/lib/pythonXX where XX is the version of Python.
Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to https://www.python.org/downloads/.
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
To use this installer python-XYZ.msi, the Windows system must support
Microsoft Installer 2.0. Save the installer file to your local machine and then run
it to find out if your machine supports MSI.
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.
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
Programs and other executable files can be in many directories, so operating systems
provide a search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by
the operating system. This variable contains information available to the command
shell and other programs.
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.
1
PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to
locate the module files imported into a program. It should include the Python
source library directory and the directories containing Python source code.
PYTHONPATH is sometimes preset by the Python installer.
2
PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is
executed every time you start the interpreter. It is named as .pythonrc.py in Unix
and it contains commands that load utilities or modify PYTHONPATH.
3
PYTHONCASEOK
It is used in Windows to instruct Python to find the first case-insensitive match in
an import statement. Set this variable to any value to activate it.
4
PYTHONHOME
It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching module
libraries easy.
Running Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a
command-line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
Here is the list of all the available command line options −
1
-d
It provides debug output.
2
-O
It generates optimized bytecode (resulting in .pyo files).
3
-S
Do not run import site to look for Python paths on startup.
4
-v
verbose output (detailed trace on import statements).
5
-X
disable class-based built-in exceptions (just use strings); obsolete starting with
version 1.6.
6
-c cmd
run Python script sent in as cmd string
7
file
run Python script from given file
or
or
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
- Subtraction Subtracts right hand operand from left hand operand. a–b=-
10
% Modulus Divides left hand operand by right hand operand and returns b%a=
remainder 0
// Floor Division - The division of operands where the result is the 9//2 = 4
quotient in which the digits after the decimal point are removed. and
But if one of the operands is negative, the result is floored, i.e., 9.0//2.0
rounded away from zero (towards negative infinity) − = 4.0, -
11//3 = -
4, -
11.0//3 =
-4.0
== If the values of two operands are equal, then the condition becomes (a == b)
true. is not
true.
<> If values of two operands are not equal, then condition becomes (a <> b)
true. is true.
This is
similar to
!=
operator.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b)
right operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the value of right (a <= b)
operand, then condition becomes true. is true.
= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c
+= Add AND It adds right operand to the left operand and assign the result c += a is
to left operand equivalent
to c = c +
a
-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c -
a
*= Multiply It multiplies right operand with the left operand and assign c *= a is
AND the result to left operand equivalent
to c = c *
a
/= Divide AND It divides left operand with the right operand and assign the c /= a is
result to left operand equivalent
to c = c /
a
%= Modulus It takes modulus using two operands and assign the result to c %= a is
AND left operand equivalent
to c = c %
a
//= Floor It performs floor division on operators and assign value to the c //= a is
Division left operand equivalent
to c = c //
a
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49
(means
0011 0001)
<< Binary Left Shift The left operands value is moved left by the number a << 2 =
of bits specified by the right operand. 240 (means
1111 0000)
>> Binary Right The left operands value is moved right by the number a >> 2 = 15
Shift of bits specified by the right operand. (means
0000 1111)
not Logical Used to reverse the logical state of its operand. Not(a
NOT and b) is
false.
not in Evaluates to true if it does not finds a variable in the specified x not in y,
sequence and false otherwise. here not
in results
in a 1 if x
is not a
member
of
sequence
y.
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
[ Show Example ]
is not Evaluates to false if the variables on either side of the operator x is not y,
point to the same object and true otherwise. here is
not results in
1 if id(x) is not
equal to id(y).
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -
@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Decision making is anticipation of conditions occurring while execution of the program
and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute
if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages −
Python programming language assumes any non-zero and non-null values as TRUE,
and if it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements.
Click the following links to check their detail.
1 if statements
2 if...else statements
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
1 while loop
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 pass statement
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
Python supports four different numerical types −
int (signed integers) − They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
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
Here are some examples of numbers
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 floating point numbers
denoted by a + bj, where a is the real part and b is the imaginary part of the
complex number.
Mathematical Functions
Python includes following functions that perform mathematical calculations.
1 abs(x)
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)
The natural logarithm of x, for x> 0
8 log10(x)
9 max(x1, x2,...)
10 min(x1, x2,...)
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the same
sign as x. The integer part is returned as a float.
12 pow(x, y)
13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero as a
tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
14 sqrt(x)
1 choice(seq)
A random item from a list, tuple, or string.
3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1
4 seed([x])
Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.
5 shuffle(lst)
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
1 acos(x)
2 asin(x)
3 atan(x)
5 cos(x)
6 hypot(x, y)
7 sin(x)
8 tan(x)
9 degrees(x)
10 radians(x)
Mathematical Constants
The module also defines two mathematical constants −
1
pi
The mathematical constant pi.
2
e
The mathematical constant e
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"
#!/usr/bin/python
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string
altogether. For example −
Live Demo
#!/usr/bin/python
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
* Repetition - Creates new strings, concatenating multiple copies of the a*2 will give
same string -HelloHello
[] Slice - Gives the character from the given index a[1] will
give e
[:] Range Slice - Gives the characters from the given range a[1:4] will
give ell
not in Membership - Returns true if a character does not exist in the given M not in a
string will give 1
r/R Raw String - Suppresses actual meaning of Escape characters. The print r'\n'
syntax for raw strings is exactly the same as for normal strings with the prints \n
exception of the raw string operator, the letter "r," which precedes the and print R'\
quotation marks. The "r" can be lowercase (r) or uppercase (R) and must n'prints \n
be placed immediately preceding the first quote mark.
#!/usr/bin/python
%c character
%o octal integer
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
- left justification
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
depending on whether 'x' or 'X' were used.
m.n. m is the minimum total width and n is the number of digits to display
after the decimal point (if appl.)
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.
Live Demo
#!/usr/bin/python
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) −
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.
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 −
Live Demo
#!/usr/bin/python
print 'C:\\nowhere'
#!/usr/bin/python
print r'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 −
Live Demo
#!/usr/bin/python
1 capitalize()
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width
columns.
Counts how many times str occurs in string or in a substring of string if starting
index beg and ending index end are given.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to
the default string encoding.
5 encode(encoding='UTF-8',errors='strict')
Determines if string or a substring of string (if starting index beg and ending index
end are given) ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize
not provided.
Determine if str occurs in string or in a substring of string if starting index beg and
ending index end are given returns index if found and -1 otherwise.
10 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic
and false otherwise.
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()
Returns true if a unicode string contains only numeric characters and false
otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
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)
Returns the length of the string
20 ljust(width[, fillchar])
21 lower()
22 lstrip()
23 maketrans()
24 max(str)
25 min(str)
Replaces all occurrences of old in string with new or at most max occurrences if
max given.
27 rfind(str, beg=0,end=len(string))
29 rjust(width,[, fillchar])
30 rstrip()
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings 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))
Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and false otherwise.
34 strip([chars])
35 swapcase()
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and
the rest are lowercase.
37 translate(table, deletechars="")
38 upper()
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters;
intended for numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false
otherwise.
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 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 datatype 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.
Creating a list is as simple as putting different comma-separated values between
square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and
so on.
#!/usr/bin/python
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 −
Live Demo
#!/usr/bin/python
#!/usr/bin/python
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
1 list.append(obj)
Appends object obj to list
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])
A tuple is a collection of objects which ordered and immutable. 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.
Creating a tuple is as simple as putting different comma-separated values. 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";
The empty tuple is written as two parentheses containing nothing −
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.
#!/usr/bin/python
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 −
Live Demo
#!/usr/bin/python
#!/usr/bin/python
This produces the 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
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these
short examples −
Live Demo
#!/usr/bin/python
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
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.
#!/usr/bin/python
#!/usr/bin/python
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 −
Live Demo
#!/usr/bin/python
#!/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
Note − del() method is discussed in subsequent section.
#!/usr/bin/python
#!/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.
3 str(dict)
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
3 dict.fromkeys()
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)
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
10 dict.values()
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?
Time intervals are floating-point numbers in units of seconds. Particular instants in time
are expressed in seconds since 00:00:00 hrs January 1, 1970(epoch).
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 00:00:00 hrs January
1, 1970(epoch).
Example
Live Demo
#!/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
What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below
−
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
The above tuple is equivalent to struct_time structure. This structure has following
attributes −
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)
7 tm_yday 1 to 366 (Julian day)
localtime = time.localtime(time.time())
print "Local current time :", localtime
This would produce the following result, which could be formatted in any other
presentable form −
Local current time : time.struct_time(tm_year=2013, tm_mon=7,
tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2,
tm_yday=198, tm_isdst=0)
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal
1 time.altzone
The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK). Only use this if daylight is nonzero.
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 approaches, the value of time.clock is more
useful than that of time.time().
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 returns a floating-
point value with the instant expressed in seconds since the epoch.
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()
Resets the time conversion rules used by the library routines. The environment
variable TZ specifies how this is done.
1 time.timezone
Attribute time.timezone is the offset in seconds of the local time zone (without
DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).
2 time.tzname
Attribute time.tzname is a pair of locale-dependent strings, which are the names
of the local time zone without and with DST, respectively.
1 calendar.calendar(year,w=2,l=1,c=6)
Returns a multiline string with a calendar for year year formatted into three
columns separated by c spaces. w is the width in characters of each date; each
line has length 21*w+18+2*c. l is the number of lines for each week.
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.
3 calendar.isleap(year)
Returns True if year is a leap year; otherwise, False.
4 calendar.leapdays(y1,y2)
Returns the total number of leap days in the years within range(y1,y2).
5 calendar.month(year,month,w=2,l=1)
Returns a multiline string with a calendar for month month of year year, one line
per week plus two header lines. w is the width in characters of each date; each
line has length 7*w+6. l is the number of lines for each week.
6 calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside month
month of year year are set to 0; days within the month are set to their day-of-
month, 1 and up.
7 calendar.monthrange(year,month)
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)
Like print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
Like print calendar.month(year,month,w,l).
10 calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday codes are 0
(Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time instant in time-tuple form and returns
the same instant as a floating-point number of seconds since the epoch.
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).
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 ( ( ) ).
Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
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.
def printme( str ):
"This prints a passed string into this function"
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 −
Live Demo
#!/usr/bin/python
Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
Live Demo
#!/usr/bin/python
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 −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
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
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
Live Demo
#!/usr/bin/python
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 −
Live Demo
#!/usr/bin/python
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python
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-length arguments and are
not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
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 −
Live Demo
#!/usr/bin/python
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python
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
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
def print_func( par ):
print "Hello : ", par
return
Locating Modules
When you import a module, the Python interpreter searches for the module in the
following sequences −
The current directory.
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/.
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
content = dir(math)
print content
Packages in Python
A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages and sub-
subpackages, and so on.
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/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
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 −
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available when
you import the Phone package.
#!/usr/bin/python
Phone.Pots()
Phone.Isdn()
Phone.G3()
#!/usr/bin/python
raw_input
input
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 −
Enter your input: Hello Python
Received input is : Hello Python
The input Function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input
is a valid Python expression and returns the evaluated result to you.
#!/usr/bin/python
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
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.
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+
Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
8
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and
writing.
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
Opens a file for appending in binary format. 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.
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 append mode. If the file does not exist, it
creates a new file for reading and writing.
12
ab+
Opens a file for both appending and reading in binary format. The file pointer is at
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.
1
file.closed
Returns true if file is closed, false otherwise.
2
file.mode
Returns access mode with which file was opened.
3
file.name
Returns name of the file.
4
file.softspace
Returns false if space explicitly required with print, true otherwise.
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
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.
Python is a great language.
Yeah its great!!
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
File Positions
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.
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
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
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
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.
1
Exception
Base class for all exceptions
2
StopIteration
Raised when the next() method of an iterator does not point to any object.
3
SystemExit
Raised by the sys.exit() function.
4
StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5
ArithmeticError
Base class for all errors that occur for numeric calculation.
6
OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7
FloatingPointError
Raised when a floating point calculation fails.
8
ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError
Raised in case of failure of the Assert statement.
10
AttributeError
Raised in case of failure of attribute reference or assignment.
11
EOFError
Raised when there is no input from either the raw_input() or input() function and
the end of file is reached.
12
ImportError
Raised when an import statement fails.
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14
LookupError
Base class for all lookup errors.
15
IndexError
Raised when an index is not found in a sequence.
16
KeyError
Raised when the specified key is not found in the dictionary.
17
NameError
Raised when an identifier is not found in the local or global namespace.
18
UnboundLocalError
Raised when trying to access a local variable in a function or method but no value
has been assigned to it.
19
EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20
IOError
Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.
21
IOError
Raised for operating system-related errors.
22
SyntaxError
Raised when there is an error in Python syntax.
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
25
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.
26
TypeError
Raised when an operation or function is attempted that is invalid for the specified
data type.
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
Raised when an abstract method that needs to be implemented in an inherited
class is not actually implemented.
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.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be
more accurate, a raise-if-not statement). An expression is tested, and if the result
comes up false, an exception is raised.
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.
The assert Statement
When it encounters an assert statement, Python evaluates the accompanying
expression, which is hopefully true. If the expression is false, Python raises
an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
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.
Example
Here is a function that converts a temperature from degrees Kelvin to degrees
Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it
sees a negative temperature −
Live Demo
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.
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
Here is simple syntax of try....except...else blocks −
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.
Here are few important points about the above-mentioned syntax −
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.
Example
This example opens a file, writes content in the, file and comes out gracefully because
there is no problem at all −
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
You cannot use else clause as well along with a finally clause.
Example
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the
following result −
Error: can't find file or read data
Same example can be written more cleanly as follows −
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
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 except statements if present in the next higher
layer of the try-except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary by exception. You capture an
exception's argument by supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
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
Following is an example for a single exception −
Live Demo
#!/usr/bin/python
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.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the
exception argument is None.
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 −
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
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:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed
from RuntimeError. This is useful when you need to display more specific information
when an exception is caught.
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):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Python has been an object-oriented language since it existed. Because of this, creating
and using classes and objects are downright easy. This chapter helps you become an
expert in using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming,
you may want to consult an introductory course on it or at least a tutorial of some sort
so that you have a grasp of the basic concepts.
However, here is small introduction of Object-Oriented Programming (OOP) to bring
you at speed −
Creating Classes
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed
via ClassName.__doc__.
The class_suite consists of all the component statements defining class
members, data attributes and functions.
Example
Following is the example of a simple Python class −
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
The variable empCount is a class variable whose value is shared among all
instances of a this class. This can be accessed as Employee.empCount from
inside the class or outside the class.
The first method __init__() is a special method, which is called class constructor
or initialization method that Python calls when you create a new instance of this
class.
You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to the
list for you; you do not need to include it when you call the methods.
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable
would be accessed using class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Now, putting all the concepts together −
Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
#!/usr/bin/python
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed
Note − Ideally, you should define your classes in separate file, then you should import
them in your main program file using import statement.
Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a preexisting
class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those
attributes as if they were defined in the child class. A child class can also override data
members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base
classes to inherit from is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Example
Live Demo
#!/usr/bin/python
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
def childMethod(self):
print 'Calling child method'
Overriding Methods
You can always override your parent class methods. One reason for overriding
parent's methods is because you may want special or different functionality in your
subclass.
Example
Live Demo
#!/usr/bin/python
1
__init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2
__del__( self )
Destructor, deletes an object
Sample Call : del obj
3
__repr__( self )
Evaluable string representation
Sample Call : repr(obj)
4
__str__( self )
Printable string representation
Sample Call : str(obj)
5
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors, what
happens when you use the plus operator to add them? Most likely Python will yell at
you.
You could, however, define the __add__ method in your class to perform vector
addition and then the plus operator would behave as per expectation −
Example
Live Demo
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Data Hiding
An object's attributes may or may not be visible outside the class definition. You need
to name attributes with a double underscore prefix, and those attributes then are not be
directly visible to outsiders.
Example
Live Demo
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
1
pattern
This is the regular expression to be matched.
2
string
This is the string, which would be searched to match the pattern at the beginning
of string.
3
flags
You can specify different flags using bitwise OR (|). These are modifiers, which
are listed in the table below.
1
group(num=0)
This method returns entire match (or specific subgroup num)
2
groups()
This method returns all matching subgroups in a tuple (empty if there weren't any)
Example
Live Demo
#!/usr/bin/python
import re
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
1
pattern
This is the regular expression to be matched.
2
string
This is the string, which would be searched to match the pattern anywhere in the
string.
3
flags
You can specify different flags using bitwise OR (|). These are modifiers, which
are listed in the table below.
1
group(num=0)
This method returns entire match (or specific subgroup num)
2
groups()
This method returns all matching subgroups in a tuple (empty if there weren't any)
Example
Live Demo
#!/usr/bin/python
import re
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
#!/usr/bin/python
import re
1
re.I
Performs case-insensitive matching.
2
re.L
Interprets words according to the current locale. This interpretation affects the
alphabetic group (\w and \W), as well as word boundary behavior(\b and \B).
3
re.M
Makes $ match the end of a line (not just the end of the string) and makes ^
match the start of any line (not just the start of the string).
4
re.S
Makes a period (dot) match any character, including a newline.
5
re.U
Interprets letters according to the Unicode character set. This flag affects the
behavior of \w, \W, \b, \B.
6
re.X
Permits "cuter" regular expression syntax. It ignores whitespace (except inside a
set [] or when escaped by a backslash) and treats unescaped # as a comment
marker.
1
^
Matches beginning of line.
2
$
Matches end of line.
3
.
Matches any single character except newline. Using m option allows it to match
newline as well.
4
[...]
Matches any single character in brackets.
5
[^...]
Matches any single character not in brackets
6
re*
Matches 0 or more occurrences of preceding expression.
7
re+
Matches 1 or more occurrence of preceding expression.
8
re?
Matches 0 or 1 occurrence of preceding expression.
9
re{ n}
Matches exactly n number of occurrences of preceding expression.
10
re{ n,}
Matches n or more occurrences of preceding expression.
11
re{ n, m}
Matches at least n and at most m occurrences of preceding expression.
12
a| b
Matches either a or b.
13
(re)
Groups regular expressions and remembers matched text.
14
(?imx)
Temporarily toggles on i, m, or x options within a regular expression. If in
parentheses, only that area is affected.
15
(?-imx)
Temporarily toggles off i, m, or x options within a regular expression. If in
parentheses, only that area is affected.
16
(?: re)
Groups regular expressions without remembering matched text.
17
(?imx: re)
Temporarily toggles on i, m, or x options within parentheses.
18
(?-imx: re)
Temporarily toggles off i, m, or x options within parentheses.
19
(?#...)
Comment.
20
(?= re)
Specifies position using a pattern. Doesn't have a range.
21
(?! re)
Specifies position using pattern negation. Doesn't have a range.
22
(?> re)
Matches independent pattern without backtracking.
23
\w
Matches word characters.
24
\W
Matches nonword characters.
25
\s
Matches whitespace. Equivalent to [\t\n\r\f].
26
\S
Matches nonwhitespace.
27
\d
Matches digits. Equivalent to [0-9].
28
\D
Matches nondigits.
29
\A
Matches beginning of string.
30
\Z
Matches end of string. If a newline exists, it matches just before newline.
31
\z
Matches end of string.
32
\G
Matches point where last match finished.
33
\b
Matches word boundaries when outside brackets. Matches backspace (0x08)
when inside brackets.
34
\B
Matches nonword boundaries.
35
\n, \t, etc.
Matches newlines, carriage returns, tabs, etc.
36
\1...\9
Matches nth grouped subexpression.
37
\10
Matches nth grouped subexpression if it matched already. Otherwise refers to the
octal representation of a character code.
1
python
Match "python".
Character classes
Sr.No Example & Description
.
1
[Pp]ython
Match "Python" or "python"
2
rub[ye]
Match "ruby" or "rube"
3
[aeiou]
Match any one lowercase vowel
4
[0-9]
Match any digit; same as [0123456789]
5
[a-z]
Match any lowercase ASCII letter
6
[A-Z]
Match any uppercase ASCII letter
7
[a-zA-Z0-9]
Match any of the above
8
[^aeiou]
Match anything other than a lowercase vowel
9
[^0-9]
Match anything other than a digit
1
.
Match any character except newline
2
\d
Match a digit: [0-9]
3
\D
Match a nondigit: [^0-9]
4
\s
Match a whitespace character: [ \t\r\n\f]
5
\S
Match nonwhitespace: [^ \t\r\n\f]
6
\w
Match a single word character: [A-Za-z0-9_]
7
\W
Match a nonword character: [^A-Za-z0-9_]
Repetition Cases
Sr.No Example & Description
.
1
ruby?
Match "rub" or "ruby": the y is optional
2
ruby*
Match "rub" plus 0 or more ys
3
ruby+
Match "rub" plus 1 or more ys
4
\d{3}
Match exactly 3 digits
5
\d{3,}
Match 3 or more digits
6
\d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition
This matches the smallest number of repetitions −
2
<.*?>
Nongreedy: matches "<python>" in "<python>perl>"
1
\D\d+
No group: + repeats \d
2
(\D\d)+
Grouped: + repeats \D\d pair
3
([Pp]ython(, )?)+
Match "Python", "Python, python, python", etc.
Backreferences
This matches a previously matched group again −
1
([Pp])ython&\1ails
Match python&pails or Python&Pails
2
(['"])[^\1]*\1
Single or double-quoted string. \1 matches whatever the 1st group matched. \2
matches whatever the 2nd group matched, etc.
Alternatives
Sr.No Example & Description
.
1
python|perl
Match "python" or "perl"
2
rub(y|le))
Match "ruby" or "ruble"
3
Python(!+|\?)
"Python" followed by one or more ! or one ?
Anchors
This needs to specify match position.
1
^Python
Match "Python" at the start of a string or internal line
2
Python$
Match "Python" at the end of a string or line
3
\APython
Match "Python" at the start of a string
4
Python\Z
Match "Python" at the end of a string
5
\bPython\b
Match "Python" at a word boundary
6
\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
7
Python(?=!)
Match "Python", if followed by an exclamation point.
8
Python(?!!)
Match "Python", if not followed by an exclamation point.
1
R(?#comment)
Matches "R". All the rest is a comment
2
R(?i)uby
Case-insensitive while matching "uby"
3
R(?i:uby)
Same as above
4
rub(?:y|le))
Group only without creating \1 backreference
The Common Gateway Interface, or CGI, is a set of standards that define how
information is exchanged between the web server and a custom script. The CGI specs
are currently maintained by the NCSA.
What is CGI?
The Common Gateway Interface, or CGI, is a standard for external gateway
programs to interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link
to browse a particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e.,
filename.
Web Server parses the URL and looks for the filename. If it finds that file then
sends it back to the browser, otherwise sends an error message indicating that
you requested a wrong file.
Web browser takes response from web server and displays either the received
file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain
directory is requested that file is not sent back; instead it is executed as a program, and
whatever that program outputs is sent back for your browser to display. This function is
called the Common Gateway Interface or CGI and the programs are called CGI scripts.
These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++
program, etc.
<Directory "/var/www/cgi-bin">
Options All
</Directory>
Here, we assume that you have Web Server up and running successfully and you are
able to run any other CGI program like Perl or Shell, etc.
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello World - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello World! This is my first CGI program</h2>'
print '</body>'
print '</html>'
HTTP Header
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the
browser to understand the content. All the HTTP header will be in the following form −
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in your CGI
Programming.
1 Content-type:
A MIME string defining the format of the file being returned. Example is Content-
type:text/html
2 Expires: Date
The date the information becomes invalid. It is used by the browser to decide
when a page needs to be refreshed. A valid date string is in the format 01 Jan
1998 12:00:00 GMT.
3 Location: URL
The URL that is returned instead of the URL requested. You can use this field to
redirect a request to any file.
4 Last-modified: Date
The date of last modification of the resource.
5 Content-length: N
The length, in bytes, of the data being returned. The browser uses this value to
report the estimated download time for a file.
6 Set-Cookie: String
Set the cookie passed through the string
2 CONTENT_LENGTH
The length of the query information. It is available only for POST requests.
3 HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
4 HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent
originating the request. It is name of the web browser.
5 PATH_INFO
The path for the CGI script.
6 QUERY_STRING
The URL-encoded information that is sent with GET method request.
7 REMOTE_ADDR
The IP address of the remote host making the request. This is useful logging or
for authentication.
8 REMOTE_HOST
The fully qualified name of the host making the request. If this information is not
available, then REMOTE_ADDR can be used to get IR address.
9 REQUEST_METHOD
The method used to make the request. The most common methods are GET and
POST.
10 SCRIPT_FILENAME
The full path to the CGI script.
11 SCRIPT_NAME
The name of the CGI script.
12 SERVER_NAME
The server's hostname or IP Address
13 SERVER_SOFTWARE
The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables. Click this link to see the
result Get Environment
#!/usr/bin/python
import os
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Here is the actual output of the above form, you enter First and Last Name and then
click submit button to see the result.
First Name:
Submit
Last Name:
Passing Information Using POST Method
A generally more reliable method of passing information to a CGI program is the POST
method. This packages the information in exactly the same way as GET methods, but
instead of sending it as a text string after a ? in the URL it sends it as a separate
message. This message comes into the CGI script in the form of the standard input.
Below is same hello_get.py script which handles GET as well as POST method.
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Let us take again same example as above which passes two values using HTML
FORM and submit button. We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form. You enter First and Last Name and then
click submit button to see the result.
First Name:
Submit
Last Name:
Passing Checkbox Data to CGI Program
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code for a form with two checkboxes −
<form action = "/cgi-bin/checkbox.cgi" method = "POST" target =
"_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
if form.getvalue('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % math_flag
print "<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
Passing Text Area Data to CGI Program
TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/textarea.py" method = "post" target =
"_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
Submit
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"
Maths Submit
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on your site, the
cookie is available for retrieval. Once retrieved, your server knows/remembers what
was stored.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies are sent along with HTTP
Header before to Content-type field. Assuming you want to set UserID and Password
as cookies. Setting the cookies is done as follows −
#!/usr/bin/python
From this example, you must have understood how to set cookies. We use Set-
Cookie HTTP header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that
cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment
variable HTTP_COOKIE and they will have following form −
key1 = value1;key2 = value2;key3 = value3....
Here is an example of how to retrieve cookies.
#!/usr/bin/python
if environ.has_key('HTTP_COOKIE'):
for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
(key, value ) = split(cookie, '=');
if key == "UserID":
user_id = value
if key == "Password":
password = value
This produces the following result for the cookies set by above script −
User ID = XYZ
Password = XYZ123
Above example has been disabled intentionally to save people uploading file on our
server, but you can try above code with your server.
Here is the script save_file.py to handle file upload −
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file
separator as follows, otherwise on your windows machine above open() statement
should work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
# HTTP Header
print "Content-Type:application/octet-stream; name = \"FileName\"\
r\n";
print "Content-Disposition: attachment; filename = \"FileName\"\r\
n\n";
str = fo.read();
print str
Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us