Python
Python
as other languages use punctuation, and it has fewer syntactical constructions than
other languages.
your programs.
within objects.
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++,
Python is copyrighted. Like Perl, Python source code is now available under the GNU
Python is now maintained by a core development team at the institute, although Guido
Python Features
maintain.
of code.
commercial databases.
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.
Win 9x/NT/2000
OS/2
PalmOS
Windows CE
Acorn/RISC OS
BeOS
Amiga
VMS/OpenVMS
QNX
VxWorks
Psion
Python has also been ported to the Java and .NET virtual machines
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is
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
Follow the link to download zipped source code available for Unix/Linux.
make
make install
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
Microsoft Installer 2.0. Save the installer file to your local machine and
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
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date. See
along with extra tools to support development on the Mac. For older Mac OS's before
Jack Jansen maintains it and you can have full access to the entire
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 operating system. This variable contains information available to the command
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.
Unix −
directory
Windows −
Python −
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
2
PYTHONSTARTUP
3
PYTHONCASEOK
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
libraries easy.
Running Python
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
1
-d
3
-S
4
-v
5
-X
6
-c cmd
7
file
or
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.
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
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
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
Hello, Python!
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
Live Demo
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now,
$ python test.py
Hello, Python!
Live Demo
#!/usr/bin/python
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
identifier is private.
private identifier.
If the identifier also ends with two trailing underscores, the identifier is a
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
assert finally or
break for pass
def if return
elif in while
else is with
or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced.
statements within the block must be indented the same amount. For
example −
if True:
print "True"
else:
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
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
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text
Multi-Line Statements
total = item_one + \
item_two + \
item_three
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.
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
Live Demo
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
Hello, Python!
expression −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
a multiline statement.
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
user presses the key, the program ends. This is a nice trick to keep a console window
Python. Compound or complex statements, such as if, while, def, and class require a
with a colon ( : ) and are followed by one or more lines which make
if expression :
suite
elif expression :
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] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
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
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.
declaration happens automatically when you assign a value to a variable. The equal
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
Live Demo
#!/usr/bin/python
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables
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
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.
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
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del
del var
del var_a, var_b
long (long integers, they can also be represented in octal and hexadecimal)
Examples
Here are some examples of numbers −
that you use only an uppercase L to avoid confusion with the number 1.
denoted by x + yj, where x and y are the real numbers and j is the
imaginary unit.
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the
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, lists
are similar to arrays in C. One difference between them is that all the items belonging
The values stored in a list can be accessed using the slice operator
and working their way to end -1. The plus (+) sign is the list
Live Demo
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
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
Live Demo
#!/usr/bin/python
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
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the
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.
2
long(x [,base] )
3
float(x)
4
complex(real [,imag])
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)
Converts s to a set.
11
dict(d)
12
frozenset(s)
13
chr(x)
14
unichr(x)
15
ord(x)
17
oct(x)
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
[ Show Example ]
[ Show Example ]
<> If values of two operands are not (a <> b) is true. This is similar to !=
equal, then condition becomes true. operator.
[ Show Example ]
Assume if a = 60; and b = 13; Now in the binary format their values
will be 0011 1100 and 0000 1101 respectively. Following table lists
operands −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
[ Show Example ]
~ Binary
(~a ) = -61 (means 1100 0011 in
Ones It is unary and has the effect of
2's complement form due to a
Compleme 'flipping' bits.
signed binary number.
nt
>> Binary The left operands value is moved right a >> 2 = 15 (means 0000 1111)
Right Shift by the number of bits specified by the
right operand.
[ Show Example ]
not Used to reverse the logical state of its Not(a and b) is false.
Logical operand.
NOT
explained below −
[ Show Example ]
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if
variable in the specified sequence and x is not a member of sequence y.
false otherwise.
[ Show Example ]
[ Show Example ]
1
**
2
~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)
3
* / % //
4
+-
5
>> <<
Bitwise 'AND'
7
^|
8
<= < > >=
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
outcome. You need to determine which action to take and which statements to execute
Python programming language assumes any non-zero and non-null values as TRUE,
1 if statements
statements.
2 if...else statements
3 nested if statements
statement(s).
Live Demo
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
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
Programming languages provide various control structures that allow for more
statement −
Python programming language provides following types of loops to handle looping
requirements.
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.
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
Causes the loop to skip the remainder of its body and immediately retest its
3 pass statement
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
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del
del var
del var_a, var_b
decimal point.
uppercase or lowercase L.
float (floating point real values) − Also called floats, they
Examples
Here are some examples of numbers
denoted by a + bj, where a is the real part and b is the imaginary part of
common type for evaluation. But sometimes, you need to coerce a number explicitly
parameter.
Mathematical Functions
Python includes following functions that perform mathematical calculations.
1 abs(x)
The absolute value of x: the (positive) distance between x and zero.
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,...)
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have
12 pow(x, y)
13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero
14 sqrt(x)
1 choice(seq)
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)
Return the arc sine of x, in radians.
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)
1
pi
2
e
Python - Strings
Strings are amongst the most popular types in Python. We can create
Live Demo
#!/usr/bin/python
var1[0]: H
var2[1:5]: ytho
Updating Strings
another string. The new value can be related to its previous value or
Live Demo
#!/usr/bin/python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented
strings.
\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
\x Character x
\xnn Hexadecimal notation, where n is in the range
0.9, a.f, or A.F
then −
[:] Range Slice - Gives the characters a[1:4] will give ell
from the given range
r/R Raw String - Suppresses actual print r'\n' prints \n and print R'\
meaning of Escape characters. The n'prints \n
syntax for raw strings is exactly the
same as for normal strings with the
exception of the raw string operator,
the letter "r," which precedes the
quotation marks. The "r" can be
lowercase (r) or uppercase (R) and
must be placed immediately
preceding the first quote mark.
example −
Live Demo
#!/usr/bin/python
Here is the list of complete set of symbols which can be used along
with % −
%o octal integer
table −
Symbol Functionality
- left justification
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines,
The syntax for triple quotes consists of three consecutive single or double quotes.
Live Demo
#!/usr/bin/python
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
Every character you put into a raw string stays the way you wrote it
Live Demo
#!/usr/bin/python
print 'C:\\nowhere'
C:\nowhere
r'expression' as follows −
Live Demo
#!/usr/bin/python
print r'C:\\nowhere'
C:\\nowhere
Unicode String
Unicode strings are stored as 16-bit Unicode. This allows for a more
to the following −
Live Demo
#!/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)
Returns a space-padded string with the original string centered to a total of
width columns.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. 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)
10 isalnum()
Returns true if string has at least 1 character and all characters are
11 isalpha()
Returns true if string has at least 1 character and all characters are
12 isdigit()
13 islower()
Returns true if string has at least 1 cased character and all cased characters
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
18 join(seq)
19 len(string)
20 ljust(width[, fillchar])
21 lower()
22 lstrip()
Removes all leading whitespace in string.
23 maketrans()
24 max(str)
25 min(str)
27 rfind(str, beg=0,end=len(string))
29 rjust(width,[, fillchar])
30 rstrip()
Removes all trailing whitespace of string.
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns
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
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing
38 upper()
39 zfill (width)
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.
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
Python has six built-in types of sequences, but the most common ones are lists and
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
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
For example −
Live Demo
#!/usr/bin/python
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
slice on the left-hand side of the assignment operator, and you can
Live Demo
#!/usr/bin/python
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
Live Demo
#!/usr/bin/python
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
do for strings.
1 cmp(list1, list2)
2 len(list)
3 max(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])
Removes and returns last object or obj from list
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
Python - Tuples
A tuple is an immutable sequence of 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.
tup1 = ();
To write a tuple containing a single value you have to include a
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
For example −
Live Demo
#!/usr/bin/python
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the
Live Demo
#!/usr/bin/python
with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For
example −
Live Demo
#!/usr/bin/python
because after del tup tuple does not exist any more −
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
No Enclosing Delimiters
Live Demo
#!/usr/bin/python
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
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
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.
simple example −
Live Demo
#!/usr/bin/python
dict['Name']: Zara
dict['Age']: 7
Live Demo
#!/usr/bin/python
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
Live Demo
#!/usr/bin/python
dict['Age']: 8
dict['School']: DPS School
Live Demo
#!/usr/bin/python
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
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
Live Demo
#!/usr/bin/python
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers
Live Demo
#!/usr/bin/python
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then
1 dict.clear()
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()
Returns a list of dict's (key, value) tuple pairs
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()
formats is a common chore for computers. Python's time and calendar modules help
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in
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
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 -
What is TimeTuple?
as shown below −
1 Month 1 to 12
2 Day 1 to 31
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)
time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a
Live Demo
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
You can format any time as per your requirement, but simple method to
Live Demo
#!/usr/bin/python
import time;
( Jan 2008 ) −
Live Demo
#!/usr/bin/python
import calendar
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])
3 time.clock( )
4 time.ctime([secs])
5 time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-
6 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-
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)
9 time.strftime(fmt[,tupletime])
Parses str according to format string fmt and returns the instant in time-
tuple format.
11 time.time( )
the epoch.
12 time.tzset()
Resets the time conversion rules used by the library routines. The
module −
Sr.No Attribute with Description
.
1
time.timezone
(without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia,
Africa).
2
time.tzname
names of the local time zone without and with DST, respectively.
By default, calendar takes Monday as the first day of the week and Sunday as the last
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
3
calendar.isleap(year)
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
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
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)
Sets the first day of each week to weekday code weekday. Weekday codes
11
calendar.timegm(tupletime)
epoch.
12
calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0
If you are interested, then here you would find a list of other
important modules and functions to play with date & time in Python −
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
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
Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these
The code block within every function starts with a colon (:) and is indented.
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
Example
The following function takes a string as input parameter and prints it on standard
screen.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
Live Demo
#!/usr/bin/python
function, the change also reflects back in the calling function. For
example −
Live Demo
#!/usr/bin/python
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
Live Demo
#!/usr/bin/python
function does not affect mylist. The function accomplishes nothing and
Function Arguments
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,
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
My string
The following example gives more clear picture. Note that the order of parameters
Live Demo
#!/usr/bin/python
Name: miki
Age 50
Default arguments
value is not provided in the function call for that argument. The
Live Demo
#!/usr/bin/python
Name: miki
Age 50
Name: miki
Age 35
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.
An asterisk (*) is placed before the variable name that holds the
Live Demo
#!/usr/bin/python
Output is:
10
Output is:
70
60
50
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
expressions.
requires an expression
Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
reasons.
Syntax
is as follows −
Live Demo
#!/usr/bin/python
Value of total : 30
Value of total : 40
expression to the caller. A return statement with no arguments is the same as return
None.
All the above examples are not returning any value. You can return a
Live Demo
#!/usr/bin/python
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
you can access a particular identifier. There are two basic scopes of
variables in Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined
This means that local variables can be accessed only inside the
accessed throughout the program body by all functions. When you call
Live Demo
#!/usr/bin/python
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.
Simply, a module is a file consisting of Python code. A module can define functions,
Example
The Python code for a module named aname normally resides in a file named
some other Python source file. The import has the following syntax −
#!/usr/bin/python
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple imports
occur.
For example, to import the function fibonacci from the module fib,
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
This provides an easy way to import all the items from a module into the current
Locating Modules
When you import a module, the Python interpreter searches for the
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.
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
Each function has its own local namespace. Class methods follow the same scoping
Python makes educated guesses on whether variables are local or global. It assumes
Therefore, in order to assign a value to a global variable within a function, you must
The statement global VarName tells Python that VarName is a global variable. Python
For example, we define a variable Money in the global namespace. Within the function
Money, we assign Money a value, therefore Python assumes Money as a local variable.
However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the
problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
by a module.
The list contains the names of all the modules, variables and
Live Demo
#!/usr/bin/python
content = dir(math)
print content
Here, the special string variable __name__ is the module's name, and __file__ is the
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
If globals() is called from within a function, it will return all the names that can be
The return type of both these functions is dictionary. Therefore, names can be
Therefore, if you want to reexecute the top-level code in a module, you can use the
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
A package is a hierarchical file directory structure that defines a single Python
Consider a file Pots.py available in Phone directory. This file has following
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Phone/__init__.py
To make all of your functions available when you've imported Phone,
After you add these lines to __init__.py, you have all of these classes available when
#!/usr/bin/python
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.
The simplest way to produce output is using the print statement where you can
converts the expressions you pass into a string and writes the result
Live Demo
#!/usr/bin/python
functions are −
raw_input
input
#!/usr/bin/python
str = raw_input("Enter your input: ")
print "Received input is : ", str
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
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 −
Python provides basic functions and methods necessary to manipulate files by default.
function. This function creates a file object, which would be utilized to call other
Syntax
file object = open(file_name [, access_mode][, buffering])
default(default behavior).
1
r
Opens a file for reading only. The file pointer is placed at the beginning of
2
rb
Opens a file for reading only in binary format. The file pointer is placed at the
3
r+
Opens a file for both reading and writing. The file pointer placed at the
4
rb+
Opens a file for both reading and writing in binary format. The file pointer
5
w
Opens a file for writing only. Overwrites the file if the file exists. If the file
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
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
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
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
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
2
file.mode
3
file.name
Returns name of the file.
4
file.softspace
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
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()
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
see how to use read() and write() methods to read and write files.
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.write( "Python is a great language.\nYeah its great!!\n")
and finally it would close that file. If you would open this file, it would have following
content.
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
Example
Let's 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
# 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
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
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
To use this module you need to import it first and then you can call any related
functions.
filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
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.
directory. You need to supply an argument to this method which contains the name of
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os
takes an argument, which is the name of the directory that you want to make the
current directory.
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
Syntax
os.getcwd()
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
method.
Syntax
os.rmdir('dirname')
Example
Following is the example to remove "/tmp/test" directory. It is required to give fully
qualified name of the directory, otherwise it would search for that directory in the
current directory.
#!/usr/bin/python
import os
directories.
them −
Standard Exceptions.
1
Exception
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
7
FloatingPointError
8
ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError
10
AttributeError
Raised when there is no input from either the raw_input() or input() function
12
ImportError
13
KeyboardInterrupt
Ctrl+c.
14
LookupError
15
IndexError
16
KeyError
17
NameError
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
22
SyntaxError
23
IndentationError
24
SystemError
Raised when the interpreter finds an internal problem, but when this error is
Raised when Python interpreter is quit by using the sys.exit() function. If not
26
TypeError
27
ValueError
Raised when the built-in function for a data type has the valid type of
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
Assertions are carried out by the assert statement, the newest keyword to Python,
Programmers often place assertions at the start of a function to check for valid input,
AssertionError exception.
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
Example
Here is a function that converts a temperature from degrees Kelvin to
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)
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
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?
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
When a Python script raises an exception, it must either handle the exception
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
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.
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
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()
Example
This example tries to open a file where you do not have write
Live Demo
#!/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 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
because it catches all exceptions but does not make the programmer identify the root
You can also use the same except statement to handle multiple exceptions
as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
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-
statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
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
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
Argument of an Exception
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,
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
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
The final argument, traceback, is also optional (and rarely used in practice), and if
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
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
from RuntimeError. This is useful when you need to display more specific information
In the try block, the user-defined exception is raised and caught in the except block.
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
and using classes and objects are downright easy. This chapter helps you become an
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
class definition.
Creating Classes
The class statement creates a new class definition. The name of the class immediately
class ClassName:
'Optional class documentation string'
class_suite
ClassName.__doc__.
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
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
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
any time −
of object.
The hasattr(obj,name) − to check if an attribute exists or
not.
Every Python class keeps following built-in attributes and they can
list.
For the above class let us try to access all these attributes −
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
free the memory space. The process by which Python periodically reclaims blocks of
object's reference count reaches zero. An object's reference count changes as the
container (list, tuple, or dictionary). The object's reference count decreases when it's
deleted with del, its reference is reassigned, or its reference goes out of scope. When
You normally will not notice when the garbage collector destroys an orphaned
instance and reclaims its space. But a class can implement the special method
destroyed. This method might be used to clean up any non memory resources used by
an instance.
Example
This __del__() destructor prints the class name of an instance that
is about to be destroyed −
Live Demo
#!/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
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
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 −
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
def childMethod(self):
print 'Calling child method'
follows −
The issubclass(sub, sup) boolean function returns true if the given subclass
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...] )
2
__del__( self )
3
__repr__( self )
5
__cmp__ ( self, x )
Object comparison
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
Vector(7,8)
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
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
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class
would replace your last line as following, then it works for you −
.........................
print counter._JustCounter__secretCount
1
2
2
other strings or sets of strings, using a specialized syntax held in a pattern. Regular
The module re provides full support for Perl-like regular expressions in Python. The re
module raises the exception re.error if an error occurs while compiling or using a
regular expression.
We would cover two important functions, which would be used to handle regular
expressions. But a small thing first: There are various characters, which would have
special meaning when they are used in regular expression. To avoid any confusion
while dealing with regular expressions, we would use Raw Strings as r'expression'.
The match Function
This function attempts to match RE pattern to string with optional flags.
1
pattern
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,
2
groups()
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!!"
flags.
Here is the syntax for this function −
1
pattern
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,
The re.search function returns a match object on success, none on failure. We use
1
group(num=0)
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!!"
checks for a match only at the beginning of the string, while search checks for a match
Example
Live Demo
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
No match!!
search --> searchObj.group() : dogs
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting
all occurrences unless max provided. This method returns modified string.
Example
Live Demo
#!/usr/bin/python
import re
1
re.I
2
re.L
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
5
re.U
Interprets letters according to the Unicode character set. This flag affects
6
re.X
comment marker.
in Python −
1
^
Matches beginning of line.
2
$
3
.
4
[...]
5
[^...]
6
re*
7
re+
8
re?
Matches 0 or 1 occurrence of preceding expression.
9
re{ n}
10
re{ n,}
11
re{ n, m}
12
a| b
Matches either a or b.
13
(re)
14
(?imx)
15
(?-imx)
Temporarily toggles off i, m, or x options within a regular expression. If in
16
(?: re)
17
(?imx: re)
18
(?-imx: re)
19
(?#...)
Comment.
20
(?= re)
21
(?! re)
22
(?> re)
Matches independent pattern without backtracking.
23
\w
24
\W
25
\s
26
\S
Matches nonwhitespace.
27
\d
28
\D
Matches nondigits.
29
\A
31
\z
32
\G
33
\b
34
\B
35
\n, \t, etc.
36
\1...\9
37
\10
Matches nth grouped subexpression if it matched already. Otherwise refers
1
python
Match "python".
Character classes
Sr.No. Example & Description
1
[Pp]ython
2
rub[ye]
3
[aeiou]
4
[0-9]
Match any digit; same as [0123456789]
5
[a-z]
6
[A-Z]
7
[a-zA-Z0-9]
8
[^aeiou]
9
[^0-9]
1
.
3
\D
4
\s
5
\S
6
\w
7
\W
Repetition Cases
Sr.No. Example & Description
1
ruby?
Match "rub" or "ruby": the y is optional
2
ruby*
3
ruby+
4
\d{3}
5
\d{3,}
6
\d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition
1
<.*>
Greedy repetition: matches "<python>perl>"
2
<.*?>
1
\D\d+
No group: + repeats \d
2
(\D\d)+
3
([Pp]ython(, )?)+
Backreferences
1
([Pp])ython&\1ails
Match python&pails or Python&Pails
2
(['"])[^\1]*\1
Alternatives
Sr.No. Example & Description
1
python|perl
2
rub(y|le))
3
Python(!+|\?)
Anchors
This needs to specify match position.
2
Python$
3
\APython
4
Python\Z
5
\bPython\b
6
\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
7
Python(?=!)
8
Python(?!!)
Match "Python", if not followed by an exclamation point.
1
R(?#comment)
2
R(?i)uby
3
R(?i:uby)
Same as above
4
rub(?:y|le))
information is exchanged between the web server and a custom script. The CGI specs
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link
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
Web browser takes response from web server and displays either the
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.
CGI Architecture Diagram
CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed
by the HTTP server are kept in a pre-configured directory. This directory is called CGI
have extension as. cgi, but you can keep your files with python extension .py as well.
httpd.conf file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<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.
/var/www/cgi-bin directory and it has following content. Before running your CGI
program, make sure you have change mode of file using chmod 755 hello.py UNIX
#!/usr/bin/python
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>'
This hello.py script is a simple Python script, which writes its output on STDOUT file,
i.e., screen. There is one important and extra feature available which is first line to be
By now you must have understood basic concept of CGI and you can write many
complicated CGI programs using Python. This script can interact with any other
HTTP Header
is sent to the browser to understand the content. All the HTTP header
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
3
Location: URL
The URL that is returned instead of the URL requested. You can use this field
4
Last-modified: Date
5
Content-length: N
The length, in bytes, of the data being returned. The browser uses this value
6
Set-Cookie: String
1
CONTENT_TYPE
The data type of the content. Used when the client is sending attached
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
5
PATH_INFO
6
QUERY_STRING
The IP address of the remote host making the request. This is useful
8
REMOTE_HOST
The fully qualified name of the host making the request. If this information
9
REQUEST_METHOD
The method used to make the request. The most common methods are GET
and POST.
10
SCRIPT_FILENAME
11
SCRIPT_NAME
12
SERVER_NAME
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
#!/usr/bin/python
import os
from your browser to web server and ultimately to your CGI Program. Most frequently,
browser uses two methods two pass this information to web server. These methods
The GET method sends the encoded user information appended to the
page request. The page and the encoded information are separated by
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box. Never
use GET method if you have password or other sensitive information to pass to the
server. The GET method has size limitation: only 1024 characters can be sent in a
request string. The GET method sends information using QUERY_STRING header and
You can pass information by simply concatenating key and value pairs along with any
URL or you can use HTML <FORM> tags to pass information using GET method.
method.
/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI
are going to use cgi module, which makes it very easy to access
passed information −
#!/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>"
First Name:
Last Name:
method. This packages the information in exactly the same way as GET methods, but
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.
First Name:
Last Name:
Passing Checkbox Data to CGI Program
Checkboxes are used when more than one option is required to be selected.
Maths Physics
Below is checkbox.cgi script to handle input given by web browser for checkbox
button.
#!/usr/bin/python
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>"
Here is example HTML code for a form with two radio buttons −
Maths Physics
#!/usr/bin/python
#!/usr/bin/python
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>"
be selected.
Here is example HTML code for a form with one drop down box −
Maths Physics
#!/usr/bin/python
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>"
maintain session information among different pages. For example, one user
registration ends after completing many pages. How to maintain user's session
In many situations, using cookies is the most efficient method of remembering and
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 −
the cookie will expire when the visitor quits the browser.
Path − The path to the directory or web page that sets the
Setting up Cookies
done as follows −
#!/usr/bin/python
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored
form −
#!/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
data. The input tag with the file type creates a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data"
action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
File:
Above example has been disabled intentionally to save people uploading file on our
server, but you can try above code with your server.
#!/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
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
it will pop up a "File Download" dialogue box to the user instead of displaying actual
content. This is very easy and can be achieved through HTTP header. This HTTP
#!/usr/bin/python
# 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
You can choose the right database for your application. Python
GadFly
mSQL
MySQL
PostgreSQL
Informix
Interbase
Oracle
Sybase
Here is the list of available Python database interfaces: Python Database Interfaces
and APIs. You must download a separate DB API module for each database you need
to access. For example, if you need to access an Oracle database as well as a MySQL
database, you must download both the Oracle and the MySQL database modules.
We would learn all the concepts using MySQL, so let us talk about MySQLdb module.
What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It
implements the Python Database API v2.0 and is built on top of the MySQL C API.
Before proceeding, you make sure you have MySQLdb installed on your
machine. Just type the following in your Python script and execute it
#!/usr/bin/python
import MySQLdb
If it produces the following result, then it means MySQLdb module is
not installed −
Note − Make sure you have root privilege to install above module.
Database Connection
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
Example
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python
import MySQLdb
and saved into db for further use, otherwise db is set to None. Next, db object is used
to create a cursor object, which in turn is used to execute SQL queries. Finally, before
coming out, it ensures that database connection is closed and resources are released.
into the database tables using execute method of the created cursor.
Example
Let us create Database table EMPLOYEE −
#!/usr/bin/python
import MySQLdb
cursor.execute(sql)
INSERT Operation
It is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record
#!/usr/bin/python
import MySQLdb
dynamically −
#!/usr/bin/python
import MySQLdb
..................................
user_id = "test123"
password = "password"
READ Operation
READ Operation on any database means to fetch some useful information from the
database.
Once our database connection is established, you are ready to make a query into this
database. You can use either fetchone() method to fetch single record or fetchall()
rows have already been extracted from the result set, then
Example
The following procedure queries all the records from EMPLOYEE table
#!/usr/bin/python
import MySQLdb
Update Operation
UPDATE Operation on any database means to update one or more records, which are
The following procedure updates all the records having SEX as 'M'. Here, we increase
Example
#!/usr/bin/python
import MySQLdb
DELETE Operation
Example
#!/usr/bin/python
import MySQLdb
Performing Transactions
Transactions are a mechanism that ensures data consistency.
at all.
The Python DB API 2.0 provides two methods to either commit or rollback a
transaction.
Example
You already know how to implement transactions. Here is again similar
example −
COMMIT Operation
Commit is the operation, which gives a green signal to database to finalize the
db.commit()
ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back
db.rollback()
Disconnecting Database
To disconnect Database connection, use close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any
outstanding transactions are rolled back by the DB. However, instead of depending on
any of DB lower level implementation details, your application would be better off
Handling Errors
There are many sources of errors. A few examples are a syntax error in an executed
SQL statement, a connection failure, or calling the fetch method for an already
The DB API defines a number of errors that must exist in each database module. The
1
Warning
2
Error
3
InterfaceError
Used for errors in the database module, not the database itself. Must
subclass Error.
4
DatabaseError
5
DataError
7
IntegrityError
8
InternalError
9
ProgrammingError
10
NotSupportedError
functionality.
Your Python scripts should handle these errors, but before using any of the above
exceptions, make sure your MySQLdb has support for that exception. You can get more
access the basic socket support in the underlying operating system, which allows you
protocols.
Python also has libraries that provide higher-level access to specific application-level
This chapter gives you understanding on most famous concept in Networking - Socket
Programming.
What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may
Sockets may be implemented over a number of different channel types: Unix domain
sockets, TCP, UDP, and so on. The socket library provides specific classes for handling
the common transports as well as a generic interface for handling the rest.
1
Domain
The family of protocols that is used as the transport mechanism. These
on.
2
type
connectionless protocols.
3
protocol
4
hostname
address.
5
port
Each server listens for clients calling on one or more ports. A port may be a
service.
explained earlier.
Once you have socket object, then you can use required functions to
functions required −
1
s.bind()
This method binds address (hostname, port number pair) to socket.
2
s.listen()
3
s.accept()
This passively accept TCP client connection, waiting until connection arrives
(blocking).
1
s.connect()
1
s.recv()
2
s.send()
This method transmits TCP message
3
s.recvfrom()
4
s.sendto()
5
s.close()
6
socket.gethostname()
A Simple Server
To write Internet servers, we use the socket function available in socket module to
create a socket object. A socket object is then used to call other functions to setup a
socket server.
Now call bind(hostname, port) function to specify a port for your service on the given
host.
Next, call the accept method of the returned object. This method waits until a client
connects to the port you specified, and then returns a connection object that represents
A Simple Client
Let us write a very simple client program which opens a connection to a given port
12345 and given host. This is very simple to create a socket client using Python's
Once you have a socket open, you can read from it like any IO object. When done,
host and port, reads any available data from the socket, and then
exits −
s.connect((host, port))
print s.recv(1024)
s.close() # Close the socket when done
Now run this server.py in background and then run above client.py to see the result.
Please check all the libraries mentioned above to work with FTP, SMTP, POP, and
IMAP protocols.
Further Readings
detail −
Python provides smtplib module, which defines an SMTP client session object that can
be used to send mail to any Internet machine with an SMTP or ESMTP listener
daemon.
Here is a simple syntax to create one SMTP object, which can later be
import smtplib
host − This is the host running your SMTP server. You can
port − If you are providing host argument, then you need to specify a
port, where SMTP server is listening. Usually this port would be 25.
parameters −
Example
Here is a simple way to send one e-mail using Python script. Try it
once −
#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Here, you have placed a basic e-mail in message, using a triple quote, taking care to
format the headers correctly. An e-mail requires a From, To, and Subject header,
To send the mail you use smtpObj to connect to the SMTP server on the local machine
and then use the sendmail method along with the message, the from address, and the
destination address as parameters (even though the from and to addresses are within
If you are not running an SMTP server on your local machine, you can use smtplib
client to communicate with a remote SMTP server. Unless you are using
provider must have provided you with outgoing mail server details
simple text. Even if you include HTML tags in a text message, it is displayed as simple
text and HTML tags will not be formatted according to HTML syntax. But Python
While sending an e-mail message, you can specify a Mime version, content type and
Example
Following is the example to send HTML content as an e-mail. Try it
once −
#!/usr/bin/python
import smtplib
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
boundaries.
A boundary is started with two hyphens followed by a unique number, which cannot
appear in the message part of the e-mail. A final boundary denoting the e-mail's final
Attached files should be encoded with the pack("m") function to have base64 encoding
before transmission.
Example
Following is the example, which sends a file /tmp/test.txt as an
#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
%s
--%s
""" % (body,marker)
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
Multiple threads within a process share the same data space with the main
instruction pointer that keeps track of where within its context it is currently running.
module −
This method call enables a fast and efficient way to create new threads in both Linux
and Windows.
The method call returns immediately and the child thread starts and calls function with
the passed list of args. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing
Example
#!/usr/bin/python
import thread
import time
while 1:
pass
high-level support for threads than the thread module discussed in the previous
section.
The threading module exposes all the methods of the thread module and provides
In addition to the methods, the threading module has the Thread class that
implements threading. The methods provided by the Thread class are as follows
run method.
still executing.
thread.
the following −
Then, override the run(self [,args]) method to implement what the thread
Once you have created the new Thread subclass, you can create an instance of it and
then start a new thread by invoking the start(), which in turn calls run() method.
Example
#!/usr/bin/python
import threading
import time
exitFlag = 0
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
Synchronizing Threads
The threading module provided with Python includes a simple-to-implement locking
mechanism that allows you to synchronize threads. A new lock is created by calling
The acquire(blocking) method of the new lock object is used to force threads to run
synchronously. The optional blocking parameter enables you to control whether the
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot
be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread
The release() method of the new lock object is used to release the lock when it is no
longer required.
Example
#!/usr/bin/python
import threading
import time
threadLock = threading.Lock()
threads = []
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
Multithreaded Priority Queue
The Queue module allows you to create a new queue object that can
get() − The get() removes and returns an item from the queue.
otherwise, False.
False.
Example
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
What is XML?
The Extensible Markup Language (XML) is a markup language much like HTML or
SGML. This is recommended by the World Wide Web Consortium and available as an
open standard.
XML is extremely useful for keeping track of small to medium amounts of data without
with XML.
The two most basic and broadly used APIs to XML data are the SAX and DOM
interfaces.
Simple API for XML (SAX) − Here, you register callbacks for
memory.
SAX obviously cannot process information as fast as DOM can when working with
large files. On the other hand, using DOM exclusively can really kill your resources,
SAX is read-only, while DOM allows changes to the XML file. Since these two different
APIs literally complement each other, there is no reason why you cannot use them
xml.sax.ContentHandler.
Your ContentHandler handles the particular tags and attributes of your flavor(s) of
XML. A ContentHandler object provides methods to handle various parsing events. Its
The methods startDocument and endDocument are called at the start and the end of
the XML file. The method characters(text) is passed character data of the XML file via
The ContentHandler is called at the start and end of each element. If the parser is not
are called. Here, tag is the element tag, and attributes is an Attributes object.
xml.sax.make_parser( [parser_list] )
method.
ErrorHandler object.
string.
ErrorHandler object.
Example
#!/usr/bin/python
import xml.sax
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
parser.parse("movies.xml")
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Stars: 2
Description: Viewable boredom
For a complete detail on SAX API documentation, please refer to standard Python SAX
APIs.
The DOM is extremely useful for random-access applications. SAX only allows you a
view of one bit of the document at a time. If you are looking at one SAX element, you
Here is the easiest way to quickly load an XML document and to create a minidom
object using the xml.dom module. The minidom object provides a simple parser
method that quickly creates a DOM tree from the XML file.
The sample phrase calls the parse( file [,parser] ) function of the minidom object to
parse the XML file designated by file into a DOM tree object.
#!/usr/bin/python
type = movie.getElementsByTagName('type')[0]
print "Type: %s" % type.childNodes[0].data
format = movie.getElementsByTagName('format')[0]
print "Format: %s" % format.childNodes[0].data
rating = movie.getElementsByTagName('rating')[0]
print "Rating: %s" % rating.childNodes[0].data
description = movie.getElementsByTagName('description')[0]
print "Description: %s" % description.childNodes[0].data
For a complete detail on DOM API documentation, please refer to standard Python
DOM APIs.
this chapter.
wxWindows http://wxpython.org.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
Enter the main event loop to take action against each event triggered by the
user.
Example
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
1 Button
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons
3 Checkbutton
The Checkbutton widget is used to display a number of options as
4 Entry
The Entry widget is used to display a single-line text field for accepting
5 Frame
6 Label
The Label widget is used to provide a single-line caption for other widgets. It
7 Listbox
8 Menubutton
9 Menu
10 Message
The Message widget is used to display multiline text fields for accepting
11 Radiobutton
12 Scale
13 Scrollbar
14 Text
15 Toplevel
16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which
17 PanedWindow
A PanedWindow is a container widget that may contain any number of
18 LabelFrame
19 tkMessageBox
Standard attributes
Let us take a look at how some of their common attributes.such as sizes, colors and
Dimensions
Colors
Fonts
Anchors
Relief styles
Bitmaps
Cursors
have the purpose of organizing widgets throughout the parent widget area. Tkinter
exposes the following geometry manager classes: pack, grid, and place.
"extension."
machines, these libraries usually end in .so (for shared object). On Windows machines,
Windows users get these headers as part of the package when they use the
Additionally, it is assumed that you have good knowledge of C or C++ to write any
For your first look at a Python extension module, you need to group
The C functions you want to expose as the interface from your module.
A table mapping the names of your functions as Python developers see them
An initialization function.
the internal Python API used to hook your module into the interpreter.
Make sure to include Python.h before any other headers you might need. You need to
follow the includes with the functions you want to call from Python.
The C Functions
The signatures of the C implementation of your functions always takes
as a void function in Python as there is in C. If you do not want your functions to return
a value, return the C equivalent of Python's None value. The Python headers define a
The names of your C functions can be whatever you like as they are never seen outside
Your C functions usually are named by combining the Python module and
pointers to your C functions into the method table for the module that usually comes
struct PyMethodDef {
char *ml_name;
PyCFunction ml_meth;
int ml_flags;
char *ml_doc;
};
This table needs to be terminated with a sentinel that consists of NULL and 0 values
Example
For the above-defined function, we have following method mapping
table −
called by the Python interpreter when the module is loaded. It is required that the
The initialization function needs to be exported from the library you will be building.
for that to happen for the particular environment in which we're compiling. All you
structure −
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
above.
extension.
Putting this all together looks like the following −
#include <Python.h>
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
Example
A simple example that makes use of all the above concepts −
#include <Python.h>
void inithelloworld(void) {
Py_InitModule3("helloworld", helloworld_funcs,
"Extension module example!");
}
Here the Py_BuildValue function is used to build a Python value. Save above code in
hello.c file. We would see how to compile and install this module to be called from
Python script.
Python and extension modules, in a standard way. Modules are distributed in source
form and built and installed via a setup script usually called setup.py as follows.
For the above module, you need to prepare following setup.py script −
Now, use the following command, which would perform all needed
compilation and linking steps, with the right compiler and linker
commands and flags, and copies the resulting dynamic library into an
appropriate directory −
have permissions to write to the site-packages directory. This usually is not a problem
on Windows.
Importing Extensions
Once you installed your extension, you would be able to import and
print helloworld.helloworld()
arguments, you can use one of the other signatures for your C
The method table containing an entry for the new function would look
like this −
The first argument to PyArg_ParseTuple is the args argument. This is the object you
will be parsing. The second argument is a format string describing the arguments as
you expect them to appear. Each argument is represented by one or more characters in
Compiling the new version of your module and importing it enables you
to invoke the new function with any number of arguments of any type −
This function returns 0 for errors, and a value not equal to 0 for success. tuple is the
PyObject* that was the C function's second argument. Here format is a C string that
(...) as per ... A Python sequence is treated as one argument per item.
Returning Values
of passing in the addresses of the values you are building, you pass
add function −
You can return two values from your function as follows, this would be cauptured
Here format is a C string that describes the Python object to build. The following
arguments of Py_BuildValue are C values from which the result is built. The PyObject*
Following table lists the commonly used code strings, of which zero or more are joined
{...} as per ... Builds Python dictionary from C values, alternating keys
and values.
Code {...} builds dictionaries from an even number of C values, alternately keys and
Python's {23:'zig','zag':42}.
Discuss Python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990. Like
Perl, Python source code is also available under the GNU General Public License (GPL).
This tutorial gives enough understanding on Python programming language.