Learn Python Programming Language
Learn Python Programming Language
Copyright tutorialspoint.com
http://www.tutorialspoint.com/python/index.htm
AUDIENCE
This tutorial is designed for software programmers who need to learn Python programming
language from scratch.
PREREQUISITES
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
PYTHON OVERVIEW
http://www.tutorialspoint.com/python/python_overview.htm
Copyright tutorialspoint.com
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License GPL.
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Python Features
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode:Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the
X Window system of Unix.
Scalable: Python provides a better structure and support for large programs than shell
scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed
below:
IT supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js
Copyright tutorialspoint.com
For most of the examples given in this tutorial, you will find a Try it option in our
website code sections at the top right corner that will take you to the online compiler.
So just make use of it and enjoy your learning.
Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand
how to set up our Python environment.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on
the official website of Python:
Python Official Website : http://www.python.org/
You can download Python documentation from the following site. The documentation is available
in HTML, PDF and PostScript formats.
Python Documentation Website : www.python.org/doc/
Install Python
Python distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the source
code manually. Compiling the source code offers more flexibility in terms of choice of features
that you require in your installation.
Here is a quick overview of installing Python on various platforms:
Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to http://www.python.org/download/
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you
need to install.
To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer
2.0. Just save the installer file to your local machine and then run it to find out if your
machine supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really easy to use.
Just accept the default settings, wait until the install is finished, and you are done.
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date. See
http://www.python.org/download/mac/ for instructions on getting the current version along with
extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3
releasedin2003, MacPython is available."
Jack Jansen maintains it and you can have full access to the entire documentation at his Web site Jack Jansen Website : http://www.cwi.nl/~jack/macpython.html
Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a
search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and other
programs.
The path variable is named as PATH in Unix or Path in Windows Unixiscase sensitive; Windowsisnot.
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.
Description
PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where
to locate the module files imported into a program. It should include the
Python source library directory and the directories containing Python source
code. PYTHONPATH is sometimes preset by the Python installer.
PYTHONSTARTUP
PYTHONCASEOK
PYTHONHOME
Running Python
There are three different ways to start Python:
1 Interactive Interpreter:
You can start Python from Unix, DOS, or any other system that provides you a command-line
interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python
# Unix/Linux
or
python%
# Unix/Linux
or
C:>python
# Windows/DOS
Description
-d
-O
-S
-v
-X
disable class-based built-in exceptions justusestrings; obsolete starting with version 1.6
-c cmd
file
script.py
# Unix/Linux
or
python% script.py
# Unix/Linux
or
C:>python script.py
# Windows/DOS
If you are not able to set up the environment properly, then you can take help from your system
admin. Make sure the Python environment is properly set up and working perfectly fine.
Note: All the examples given in subsequent chapters are executed with Python 2.4.3 version
available on CentOS flavor of Linux.
We already have set up Python Programming environment online, so that you can execute all the
available examples online at the same time when you are learning theory. Feel free to modify any
example and execute it online.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
The Python language has many similarities to Perl, C, and Java. However, there are some definite
differences between the languages.
$ 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:
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print statement with
parenthesis as in print " Hello, Python! " ;. However in Python version 2.4.3, this produces the
following result:
Hello, Python!
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as
follows
$ python test.py
Let us try another way to execute a Python script. Here is the modified test.py file
#!/usr/bin/python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this
program as follows
$ chmod +x test.py
$./test.py
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters,
underscores and digits 0to9.
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.
Here are naming conventions for Python identifiers
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them
as constant or variable or any other identifier names. All the Python keywords contain lowercase
letters only.
And
exec
Not
Assert
finally
or
Break
for
pass
Class
from
Continue
global
raise
def
if
return
del
import
try
elif
in
while
else
is
with
except
lambda
yield
else:
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block.
The following example has various statement blocks
Note: Do not try to understand the logic at this point of time. Just make sure you understood
various blocks even if they are without braces.
#!/usr/bin/python
import sys
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
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or brackets do not need to use the line continuation
character. For example
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python accepts single , double " and triple quotes to denote string literals, as long as the same
type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following
are legal
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign # that is not inside a string literal begins a comment. All characters after the # and up
to the end of the physical line are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
You can type a comment on the same line after a statement or expression
name = "Madisetti" # This is again comment
This is a comment.
This is a comment, too.
This is a comment, too.
I said that already.
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses
the key, the program ends. This is a nice trick to keep a console window open until the user is done
with an application.
You can also program your script in such a way that it should accept various options. Command
Line Arguments is an advanced topic and should be studied a bit later once you have gone
through rest of the Python concepts.
Loading [MathJax]/jax/element/mml/optable/GeneralPunctuation.js
Copyright tutorialspoint.com
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals or characters in these variables.
# An integer assignment
# A floating point
# A string
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For example
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the
del statement is
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example
del var
del var_a, var_b
Examples
Here are some examples of numbers
int
long
float
complex
10
51924361L
0.0
3.14j
100
-0x19323L
15.20
45.j
-786
0122L
-21.9
9.322e-36j
080
0xDEFABCECBDAECBFBAEl
32.3+e18
.876j
-0490
535633629843L
-90.
-.6545+0J
-0x260
-052318172735L
-32.54e100
3e+26J
0x69
-4721885298529L
70.2-E12
4.53e-7j
Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
A complex number consists of an ordered pair of real floating-point numbers 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 asterisk is the repetition operator.
For example
#!/usr/bin/python
str = 'Hello World!'
print
print
print
print
print
print
str
str[0]
str[2:5]
str[2:]
str * 2
str + "TEST"
#
#
#
#
#
#
Prints
Prints
Prints
Prints
Prints
Prints
complete string
first character of the string
characters starting from 3rd to 5th
string starting from 3rd character
string two times
concatenated string
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 to a list can be of different data type.
The values stored in a list can be accessed using the slice operator []and[: ] with indexes starting at
0 in the beginning of the list and working their way to end -1. The plus + sign is the list
concatenation operator, and the asterisk is the repetition operator. For example
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print
print
print
print
print
print
list
# Prints complete list
list[0]
# Prints first element of the list
list[1:3]
# Prints elements starting from 2nd till 3rd
list[2:]
# Prints elements starting from 3rd element
tinylist * 2 # Prints list two times
list + tinylist # Prints concatenated lists
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets [] and their
elements and size can be changed, while tuples are enclosed in parentheses ( ) and cannot be
updated. Tuples can be thought of as read-only lists. For example
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2
tinytuple = (123, 'john')
print
print
print
print
print
print
tuple
# Prints complete list
tuple[0]
# Prints first element of the list
tuple[1:3]
# Prints elements starting from 2nd till 3rd
tuple[2:]
# Prints elements starting from 3rd element
tinytuple * 2
# Prints list two times
tuple + tinytuple # Prints concatenated lists
The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000
# Invalid syntax with tuple
list[2] = 1000
# Valid syntax with list
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found
in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces and values can be assigned and accessed using square
braces []. For example
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2]
= "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print
print
print
print
print
dict['one']
# Prints value for 'one' key
dict[2]
# Prints value for 2 key
tinydict
# Prints complete dictionary
tinydict.keys()
# Prints all the keys
tinydict.values() # Prints all the values
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are
"out of order"; they are simply unordered.
Description
intx[, base]
longx[, base]
floatx
complexreal[, imag]
strx
reprx
evalstr
tuples
Converts s to a tuple.
lists
Converts s to a list.
sets
Converts s to a set.
dictd
frozensets
chrx
unichrx
ordx
hexx
octx
http://www.tutorialspoint.com/python/python_basic_operators.htm
Operators are the constructs which can manipulate the value of operands.
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
Comparison Relational Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
Description
Example
+ Addition
a + b = 30
- Subtraction
a b = -10
*
Multiplication
a * b = 200
/ Division
b/a=2
% Modulus
b%a=0
** Exponent
//
Description
Example
==
a == b is not true.
!=
<>
>
<
a < b is true.
>=
<=
a <= b is true.
Description
Example
+= Add
AND
c += a is equivalent to c = c + a
-=
Subtract
AND
c -= a is equivalent to c = c - a
*=
Multiply
AND
c *= a is equivalent to c = c * a
/= Divide
AND
c /= a is equivalent to c = c / ac /= a is
equivalent to c = c / a
%=
Modulus
AND
c %= a is equivalent to c = c % a
**=
Exponent
c **= a is equivalent to c = c ** a
AND
operand
//= Floor
Division
c //= a is equivalent to c = c // a
Description
Example
& Binary
AND
| Binary OR
a | b = 61 means00111101
^ Binary
XOR
ab = 49 means00110001
~ Binary
Ones
Complement
<< Binary
Left Shift
>> Binary
Right Shift
a >> = 15 means00001111
a & b means00001100
[ Show Example ]
Operator
Description
Example
in
x in y, here in results in a 1 if x is a
member of sequence y.
not in
Description
Example
is
is not
Description
**
Exponentiation raisetothepower
~+-
Ccomplement, unary plus and minus method names for the last two
are +@ and -@
* / % //
+-
>> <<
&
Bitwise 'AND'
^|
Comparison operators
<> == !=
Equality operators
= %= /= //= -= +=
*= **=
Assignment operators
is is not
Identity operators
in not in
Membership operators
not or and
Logical operators
Copyright tutorialspoint.com
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You
need to determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages
Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements. Click the
following links to check their detail.
Statement
Description
if statements
if...else statements
nested if statements
Loading [MathJax]/jax/output/HTML-CSS/jax.js
PYTHON LOOPS
http://www.tutorialspoint.com/python/python_loops.htm
Copyright tutorialspoint.com
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute a
block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement
Python programming language provides following types of loops to handle looping requirements.
Loop Type
Description
while loop
for loop
nested loops
You can use one or more loop inside any another while, for or
do..while loop.
Description
break statement
continue statement
Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
pass statement
PYTHON NUMBERS
Copyright tutorialspoint.com
http://www.tutorialspoint.com/python/python_numbers.htm
Number data types store numeric values. They are immutable data types, means that changing
the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of
the del statement is
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
del var
del var_a, var_b
Examples
Here are some examples of numbers
int
long
float
complex
10
51924361L
0.0
3.14j
100
-0x19323L
15.20
45.j
-786
0122L
-21.9
9.322e-36j
080
0xDEFABCECBDAECBFBAEL
32.3+e18
.876j
-0490
535633629843L
-90.
-.6545+0J
-0x260
-052318172735L
-32.54e100
3e+26J
0x69
-4721885298529L
70.2-E12
4.53e-7j
Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
A complex number consists of an ordered pair of real floating point numbers denoted by a +
bj, where a is the real part and b is the imaginary part of the complex number.
Mathematical Functions
Python includes following functions that perform mathematical calculations.
Function
absx
ceilx
cmpx, y
expx
fabsx
floorx
logx
log10x
maxx1, x2, . . .
minx1, x2, . . .
modfx
Returns description
The absolute value of x: the positive distance between x and zero.
-1 if x < y, 0 if x == y, or 1 if x > y
The exponential of x: e x
powx, y
roundx[, n]
sqrtx
x rounded to n digits from the decimal point. Python rounds away from
zero as a tie-breaker: round0.5 is 1.0 and round0.5 is -1.0.
The square root of x for x > 0
randrange
[start, ]stop[, step]
Description
A random item from a list, tuple, or string.
random
A random float r, such that 0 is less than or equal to r and r is less than
1
seed[x]
shufflelst
uniformx, 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.
Function
acosx
asinx
atanx
Description
Return the arc cosine of x, in radians.
atan2y, x
cosx
hypotx, y
sinx
tanx
degreesx
radiansx
Mathematical Constants
The module also defines two mathematical constants
Constants
Description
pi
Loading [MathJax]/jax/output/HTML-CSS/jax.js
PYTHON STRINGS
http://www.tutorialspoint.com/python/python_strings.htm
Copyright tutorialspoint.com
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as
simple as assigning a value to a variable. For example
var1 = 'Hello World!'
var2 = "Python Programming"
Updating Strings
You can "update" an existing string by reassigning a variable to another string. The new value can
be related to its previous value or to a completely different string altogether. For example
#!/usr/bin/python
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
Hello Python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash
notation
Hexadecimal
character
Description
\a
0x07
Bell or alert
\b
0x08
Backspace
\cx
Control-x
\C-x
Control-x
\e
0x1b
Escape
\f
0x0c
Formfeed
\M-\C-x
\n
Meta-Control-x
0x0a
\nnn
Newline
Octal notation, where n is in the range 0.7
\r
0x0d
Carriage return
\s
0x20
Space
\t
0x09
Tab
\v
0x0b
Vertical tab
\x
Character x
\xnn
Description
Example
[]
[:]
in
H in a will give 1
not in
r/R
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
Here is the list of complete set of symbols which can be used along with %
Format
Symbol
Conversion
%c
character
%s
%i
%d
%u
%o
octal integer
%x
%X
%e
%E
%f
%g
%G
Other supported symbols and functionality are listed in the following table
Symbol
Functionality
left justification
<sp>
var
m.n.
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including
verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str
When the above code is executed, it produces the following result. Note how every single special
character has been converted to its printed form, right down to the last NEWLINE at the end of the
string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an
explicit carriage return at the end of a line or its escape code \n
this is a long string that is made up of
several lines and non-printable characters such as
TAB (
) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
Raw strings do not treat the backslash as a special character at all. Every character you put into a
raw string stays the way you wrote it
#!/usr/bin/python
print 'C:\\nowhere'
Now let's make use of raw string. We would put expression in r'expression' as follows
#!/usr/bin/python
print r'C:\\nowhere'
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16bit Unicode. This allows for a more varied set of characters, including special characters from most
languages in the world. I'll restrict my treatment of Unicode strings to the following
#!/usr/bin/python
print u'Hello, world!'
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
centerwidth, fillchar
Returns a space-padded string with the original string centered to a total of width columns.
expandtabstabsize = 8
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
Determine if str occurs in string or in a substring of string if starting index beg and ending
index end are given returns index if found and -1 otherwise.
9
10
isalnum
Returns true if string has at least 1 character and all characters are alphanumeric and
false otherwise.
11
isalpha
Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
12
isdigit
Returns true if string contains only digits and false otherwise.
13
islower
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
14
isnumeric
Returns true if a unicode string contains only numeric characters and false otherwise.
15
isspace
Returns true if string contains only whitespace characters and false otherwise.
16
istitle
Returns true if string is properly "titlecased" and false otherwise.
17
isupper
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
18
joinseq
Merges concatenates the string representations of elements in sequence seq into a string,
with separator string.
19
19
lenstring
Returns the length of the string
20
ljustwidth[, fillchar]
Returns a space-padded string with the original string left-justified to a total of width
columns.
21
lower
Converts all uppercase letters in string to lowercase.
22
lstrip
Removes all leading whitespace in string.
23
maketrans
Returns a translation table to be used in translate function.
24
maxstr
Returns the max alphabetical character from the string str.
25
minstr
Returns the min alphabetical character from the string str.
26
27
28
29
rjustwidth, [, fillchar]
Returns a space-padded string with the original string right-justified to a total of width
columns.
30
30
rstrip
Removes all trailing whitespace of string.
31
splitstr="", num=string.count(str)
Splits string according to delimiter str space if not provided and returns list of substrings;
split into at most num substrings if given.
32
splitlines num=string.count('\n')
Splits string at all or num NEWLINEs and returns a list of each line with NEWLINEs removed.
33
startswithstr, 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]
Performs both lstrip and rstrip on string
35
swapcase
Inverts case for all letters in string.
36
title
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest
are lowercase.
37
translatetable, deletechars=""
Translates string according to translation table str256 chars, removing those in the del
string.
38
upper
Converts lowercase letters in string to uppercase.
39
zfill width
Returns original string leftpadded with zeros to a total of width characters; intended for
numbers, zfill retains any sign given less one zero.
40
isdecimal
Returns true if a unicode string contains only decimal characters and false otherwise.
PYTHON LISTS
http://www.tutorialspoint.com/python/python_lists.htm
Copyright tutorialspoint.com
The most basic data structure in Python is the sequence. Each element of a sequence is assigned
a number - its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which
we would see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing,
slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions
for finding the length of a sequence and for finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list of commaseparated values items between square brackets. Important thing about a list is that items in a list
need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.
For example
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add to elements in a list with the append method. For example
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Results
Description
len[1, 2, 3]
Length
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
Concatenation
['Hi!'] * 4
Repetition
3 in [1, 2, 3]
True
Membership
123
Iteration
Python Expression
Results
Description
L[2]
'SPAM!'
L[-2]
'Spam'
L[1:]
['Spam', 'SPAM!']
lenlist
Gives the total length of the list.
maxlist
Returns item from the list with max value.
minlist
Returns item from the list with min value.
listseq
Converts a tuple into list.
list.countobj
Returns count of how many times obj occurs in list
list.extendseq
list.indexobj
Returns the lowest index in list that obj appears
list.insertindex, obj
Inserts object obj into list at offset index
list.popobj = list[ 1]
Removes and returns last object or obj from list
list.removeobj
Removes object obj from list
list.reverse
Reverses objects of list in place
list.sort[func]
Sorts objects of list, use compare func if given
Loading [MathJax]/jax/output/HTML-CSS/jax.js
PYTHON TUPLES
http://www.tutorialspoint.com/python/python_tuples.htm
Copyright tutorialspoint.com
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
To write a tuple containing a single value you have to include a comma, even though there is only
one value
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements.
You are able to take portions of existing tuples to create new tuples as the following example
demonstrates
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3
This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist any more
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Results
Description
len(1, 2, 3)
Length
1, 2, 3 + 4, 5, 6
1, 2, 3, 4, 5, 6
Concatenation
Hi! ,
Repetition
3 in 1, 2, 3
True
Membership
for x in 1, 2, 3: print x,
123
Iteration
*4
Python Expression
Results
Description
L[2]
'SPAM!'
L[-2]
'Spam'
L[1:]
['Spam', 'SPAM!']
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets
for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz'
x, y = 1, 2;
print "Value of x , y : ", x,y
lentuple
Gives the total length of the tuple.
maxtuple
Returns item from the tuple with max value.
mintuple
Returns item from the tuple with min value.
tupleseq
Converts a list into tuple.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
PYTHON DICTIONARY
http://www.tutorialspoint.com/python/python_dictionary.htm
Copyright tutorialspoint.com
Each key is separated from its value by a colon : , the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty dictionary without any items is written with just
two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of
any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error
as follows
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice']
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry as shown below in the simple example
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
dict['Age']: 8
dict['School']:
DPS School
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name'
dict.clear();
# remove all entries in dict
del dict ;
# delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because after del dict
dictionary does not exist any more
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Manni
b Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys
but something like ['key'] is not allowed. Following is a simple example:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name']
lendict
Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
strdict
Produces a printable string representation of a dictionary
typevariable
Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.
dict.copy
Returns a shallow copy of dictionary dict
dict.fromkeys
Create a new dictionary with keys from seq and values set to value.
dict.has_keykey
Returns true if key in dictionary dict, false otherwise
dict.items
Returns a list of dict's key, value tuple pairs
dict.keys
Returns list of dictionary dict's keys
dict.updatedict2
Adds dictionary dict2's key-values pairs to dict
10
dict.values
Returns list of dictionary dict's values
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
A Python program can handle date and time in several ways. Converting between date formats is a
common chore for computers. Python's time and calendar modules help track dates and times.
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in time are
expressed in seconds since 12:00am, January 1, 1970epoch.
There is a popular time module available in Python which provides functions for working with
times, and for converting between representations. The function time.time returns the current
system time in ticks since 12:00am, January 1, 1970epoch.
Example
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in
this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime
in 2038 for UNIX and Windows.
What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below
Index
Field
Values
4-digit year
2008
Month
1 to 12
Day
1 to 31
Hour
0 to 23
Minute
0 to 59
Second
0 to 61 60or61areleap seconds
Day of Week
0 to 6 0isMonday
Day of year
1 to 366 Julianday
Daylight savings
The above tuple is equivalent to struct_time structure. This structure has following attributes
Index
Attributes
Values
tm_year
2008
tm_mon
1 to 12
tm_mday
1 to 31
tm_hour
0 to 23
tm_min
0 to 59
tm_sec
0 to 61 60or61areleap seconds
tm_wday
0 to 6 0isMonday
tm_yday
1 to 366 Julianday
tm_isdst
This would produce the following result, which could be formatted in any other presentable form
Local current time : time.struct_time(tm_year=2013, tm_mon=7,
tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)
time.asctime[tupletime]
Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11
18:07:14 2008'.
time.clock
Returns the current CPU time as a floating-point number of seconds. To measure
computational costs of different approaches, the value of time.clock is more useful than
that of time.time.
time.ctime[secs]
Like asctimelocaltime(secs) and without arguments is like asctime
time.gmtime[secs]
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with
the UTC time. Note : t.tm_isdst is always 0
time.localtime[secs]
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with
the local time t. tmisdstis0or1, dependingonwhetherDSTappliestoinstantsecsbylocalrules.
time.mktimetupletime
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.
time.sleepsecs
Suspends the calling thread for secs seconds.
time.strftimefmt[, tupletime]
Accepts an instant expressed as a time-tuple in local time and returns a string
representing the instant as specified by string fmt.
10
time.strptimestr, fmt =
Parses str according to format string fmt and returns the instant in time-tuple format.
11
time.time
Returns the current time instant, a floating-point number of seconds since the epoch.
12
time.tzset
Resets the time conversion rules used by the library routines. The environment variable TZ
specifies how this is done.
time.timezone
Attribute time.timezone is the offset in seconds of the local time zone withoutDST from UTC
> 0intheAmericas; <= 0inmostofEurope, Asia, Africa.
time.tzname
Attribute time.tzname is a pair of locale-dependent strings, which are the names of the
local time zone without and with DST, respectively.
calendar.calendaryear, w = 2, l = 1, c = 6
Returns a multiline string with a calendar for year year formatted into three columns
separated by c spaces. w is the width in characters of each date; each line has length
21*w+18+2*c. l is the number of lines for each week.
2
calendar.firstweekday
Returns the current setting for the weekday that starts each week. By default, when
calendar is first imported, this is 0, meaning Monday.
calendar.isleapyear
Returns True if year is a leap year; otherwise, False.
calendar.leapdaysy1, y2
Returns the total number of leap days in the years within rangey1, y2.
calendar.monthyear, 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.
calendar.monthcalendaryear, month
Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of
year year are set to 0; days within the month are set to their day-of-month, 1 and up.
calendar.monthrangeyear, month
Returns two integers. The first one is the code of the weekday for the first day of the month
month in year year; the second one is the number of days in the month. Weekday codes
are 0 Monday to 6 Sunday; month numbers are 1 to 12.
calendar.prcalyear, w = 2, l = 1, c = 6
Like print calendar.calendaryear, w, l, c.
calendar.prmonthyear, month, w = 2, l = 1
Like print calendar.monthyear, month, w, l.
10
calendar.setfirstweekdayweekday
Sets the first day of each week to weekday code weekday. Weekday codes are 0 Monday to
6 Sunday.
11
calendar.timegmtupletime
The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the
same instant as a floating-point number of seconds since the epoch.
12
PYTHON FUNCTIONS
http://www.tutorialspoint.com/python/python_functions.htm
Copyright tutorialspoint.com
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print, etc. but you can also
create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses (
).
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
The code block within every function starts with a colon : and is indented.
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme function
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
Here, we are maintaining reference of the passed object and appending values in the same object.
So, this would produce the following result
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within the function does
not affect mylist. The function accomplishes nothing and finally this would produce the following
result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
To call the function printme, you definitely need to pass one argument, otherwise it gives a syntax
error as follows
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme function in the following ways
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
The following example gives more clear picture. Note that the order of parameters does not
matter.
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it
prints default age if it is not passed
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call. Following is a simple example
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
Syntax
The syntax of lambda functions contains only a single statement, which is as follows
lambda [arg1 [,arg2,.....argn]]:expression
30
40
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python
Global variables
Local variables
Loading [MathJax]/jax/output/HTML-CSS/jax.js
PYTHON MODULES
http://www.tutorialspoint.com/python/python_modules.htm
Copyright tutorialspoint.com
A module allows you to logically organize your Python code. Grouping related code into a module
makes the code easier to understand and use. A module is a Python object with arbitrarily named
attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's
an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches before
importing a module. For example, to import the module hello.py, you need to put the following
command at the top of the script
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("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, use the following statement
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces
the item fibonacci from the module fib into the global symbol table of the importing module.
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences
The current directory.
If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path
variable contains the current directory, PYTHONPATH, and the installation-dependent default.
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
Here, the special string variable __name__ is the module's name, and __file__ is the filename from
which the module was loaded.
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 application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above
Phone/Isdn.py file having function Isdn
Phone/G3.py file having function G3
Now, create one more file __init__.py in Phone directory
Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit
import statements in __init__.py as follows
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available when you import the
Phone package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
In the above example, we have taken example of a single functions in each file, but you can keep
multiple functions in your files. You can also define different Python classes in those files and then
you can create your packages out of those classes.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
This chapter covers all the basic I/O functions available in Python. For more functions, please refer
to standard Python documentation.
This prompts you to enter any string and it would display same string on the screen. When I typed
"Hello Python!", its output is like this
Enter your input: Hello Python
Received input is : Hello Python
This would produce the following result against the entered input
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Syntax
file object = open(file_name [, access_mode][, buffering])
Description
Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
rb+
Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
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.
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.
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
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.
Description
file.closed
file.mode
file.name
file.softspace
Example
#!/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
Syntax
fileObject.close();
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
foo.txt
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");
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it
would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts
reading from the beginning of the file and if count is missing, then it tries to read as much as
possible, maybe until the end of file.
Example
Python is
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 seekoffset[, from] method changes the current file position. The offset argument indicates the
number of bytes to be moved. The from argument specifies the reference position from where the
bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use
the current position as the reference position and if it is set to 2 then the end of the file would be
taken as the reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
The rename method takes two arguments, the current filename and the new 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
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt
#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem handling these too.
The os module has several methods that help you create, remove, and change directories.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("test")
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory
#!/usr/bin/python
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
Syntax
os.getcwd()
Example
Following is the example to give current directory
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
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
# This would remove "/tmp/test"
os.rmdir( "/tmp/test" )
directory.
manipulate files & directories on Windows and Unix operating systems. They are as follows
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
Copyright tutorialspoint.com
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them
Exception Handling: This would be covered in this tutorial. Here is a list standard
Exceptions available in Python: Standard Exceptions.
Assertions: This would be covered in Assertions in Python tutorial.
List of Standard Exceptions
EXCEPTION NAME
DESCRIPTION
Exception
StopIteration
SystemExit
StandardError
ArithmeticError
OverflowError
FloatingPointError
ZeroDivisonError
AssertionError
AttributeError
EOFError
ImportError
KeyboardInterrupt
LookupError
IndexError
KeyError
NameError
UnboundLocalError
EnvironmentError
IOError
IOError
SyntaxError
IndentationError
SystemError
SystemExit
ValueError
RuntimeError
NotImplementedError
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with your testing
of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement
ortobemoreaccurate, araise if notstatement. An expression is tested, and if the result comes up false, an
exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in
version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after a
function call to check for valid output.
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
AssertionError exceptions can be caught and handled like any other exception using the try-except
statement, but if not handled, they will terminate the program and produce a traceback.
Example
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since
zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions. In general, when a Python script encounters a situation that it
cannot cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block. After the try: block, include an except: statement,
followed by a block of code which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
You can also provide a generic except clause, which handles any exception.
After the except clauses, you can include an else-clause. The code in the else-block executes
if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
Example
This example opens a file, writes content in the, file and comes out gracefully because there is no
problem at all
#!/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 permission, so it raises an exception
#!/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"
This kind of a try-except statement catches all the exceptions that occur. Using this kind of tryexcept statement is not considered a good programming practice though, because it catches all
exceptions but does not make the programmer identify the root cause of the problem that may
occur.
Note that you can provide except clauses, or a finally clause, but not both. You cannot use else
clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the following
result:
Error: can't find file or read data
When an exception is thrown in the try block, the execution immediately passes to the finally
block. After all the statements in the finally block are executed, the exception is raised again and is
handled in the except statements if present in the next higher layer of the try-except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional information about the
problem. The contents of the argument vary by exception. You capture an exception's argument
by supplying a variable in the except clause as follows
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.
Example
Following is an example for a single exception
#!/usr/bin/python
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");
Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general syntax for the
raise statement is as follows.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception forexample, NameError and argument is a value for the
exception argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional andrarelyusedinpractice, and if present, is the traceback
object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python core
raises are classes, with an argument that is an instance of the class. Defining new exceptions is
quite easy and can be done as follows
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: In order to catch an exception, an "except" clause must refer to the same exception thrown
either class object or simple string. For example, to capture above exception, we must write the
except clause as follows
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e
is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
Python has been an object-oriented language since it existed. Because of this, creating and using
classes and objects are downright easy. This chapter helps you become an expert in using Python's
object-oriented programming support.
If you do not have any previous experience with object-oriented OO programming, you may want
to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of
the basic concepts.
However, here is small introduction of Object-Oriented Programming OOP to bring you at speed
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows the
keyword class followed by a colon as follows
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example
Following is the example of a simple Python class
class Employee:
'Common base class for all employees'
empCount = 0
def __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,
The variable empCount is a class variable whose value is shared among all instances of a
this class. This can be accessed as Employee.empCount from inside the class or outside the
class.
The first method __init__ is a special method, which is called class constructor or initialization
method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you do not
need to include it when you call the methods.
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
You can add, remove, or modify attributes of classes and objects at any time
emp1.age = 7
emp1.age = 8
del emp1.age
Instead of using the normal statements to access attributes, you can use the following functions
The getattrobj, name[, default] : to access the attribute of object.
The hasattrobj, name : to check if an attribute exists or not.
The setattrobj, name, value : to set an attribute. If attribute does not exist, then it would be
created.
The delattrobj, name : to delete an attribute.
hasattr(emp1,
getattr(emp1,
setattr(emp1,
delattr(empl,
'age')
#
'age')
#
'age', 8) #
'age')
#
"Employee.__doc__:", Employee.__doc__
"Employee.__name__:", Employee.__name__
"Employee.__module__:", Employee.__module__
"Employee.__bases__:", Employee.__bases__
"Employee.__dict__:", Employee.__dict__
of <40>
of <40>
del a
b = 100
c[0] = -1
of <40>
of <40>
of <40>
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 __del__, called a destructor, that
is invoked when the instance is about to be 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
#!/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 members and methods from
the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base classes to inherit
from is given after the class name
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Example
#!/usr/bin/python
class Parent:
# define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child()
c.childMethod()
c.parentMethod()
c.setAttr(200)
c.getAttr()
# instance of child
# child calls its method
# calls parent's method
# again call parent's method
# again call parent's method
Similar way, you can drive a class from multiple parent classes as follows
class A:
.....
class B:
.....
# subclass of A and B
You can use issubclass or isinstance functions to check a relationships of two classes and
instances.
The issubclasssub, sup boolean function returns true if the given subclass sub is indeed a
subclass of the superclass sup.
The isinstanceobj, Class boolean function returns true if obj is an instance of class Class or is
an instance of a subclass of Class
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
#!/usr/bin/python
class Parent:
# define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
c = Child()
c.myMethod()
# instance of child
# child calls overridden method
__del__self
Destructor, deletes an object
Sample Call : del obj
__repr__self
Evaluatable string representation
Sample Call : reprobj
__str__self
Printable string representation
Sample Call : strobj
__cmp__ self, x
Object comparison
Sample Call : cmpobj, x
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors, what happens
when you use the plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition and then
the plus operator would behave as per expectation
Example
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to name
attributes with a double underscore prefix, and those attributes then are not be directly visible to
outsiders.
Example
#!/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
Python protects those members by internally changing the name to include the class name. You
can access such attributes as object._className__attrName. If you would replace your last line as
following, then it works for you
.........................
print counter._JustCounter__secretCount
Copyright tutorialspoint.com
A regular expression is a special sequence of characters that helps you match or find other strings
or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used
in UNIX world.
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'.
Description
pattern
string
flags
The re.match function returns a match object on success, None on failure. We usegroupnum or
groups function of match object to get matched expression.
Match Object Methods
Description
groupnum = 0
groups
Example
#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
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!!"
Description
pattern
string
flags
The re.search function returns a match object on success, none on failure. We use groupnum or
groups function of match object to get matched expression.
Match Object Methods
Description
groupnum = 0
groups
Example
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
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!!"
Example
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print "match --> matchObj.group() : ", matchObj.group()
else:
print "No match!!"
searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
print "search --> searchObj.group() : ", searchObj.group()
else:
print "Nothing found!!"
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
#!/usr/bin/python
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print "Phone Num : ", num
2004-959-559
2004959559
Regular expression literals may include an optional modifier to control various aspects of
matching. The modifiers are specified as an optional flag. You can provide multiple modifiers
using exclusive OR | , as shown previously and may be represented by one of these
Modifier
Description
re.I
re.L
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).
re.S
re.U
re.X
Description
[...]
[^...]
re*
re+
re?
re{ n}
re{ n,}
re{ n, m}
a| b
Matches either a or b.
re
?imx
? imx
?imx: re
? imx: re
?#...
Comment.
? = re
? !re
? > re
\w
\W
\s
\S
Matches nonwhitespace.
\d
\D
Matches nondigits.
\A
\Z
\z
\G
\b
\B
\1...\9
\10
Description
python
Match "python".
Character classes
Example
Description
[Pp]ython
rub[ye]
[aeiou]
[0-9]
[a-z]
[A-Z]
[a-zA-Z0-9]
[^aeiou]
[^0-9]
Description
\d
\D
\s
\S
\w
\W
Repetition Cases
Example
Description
ruby?
ruby*
ruby+
\d{3}
\d{3,}
\d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition
This matches the smallest number of repetitions
Example
Description
<.*>
<.*?>
Description
\D\d+
No group: + repeats \d
\D\d+
[Pp]ython(, ?)+
Backreferences
This matches a previously matched group again
Example
Description
[Pp]ython&\1ails
['"][^\1]*\1
Alternatives
Example
Description
python|perl
ruby|le)
Python!+|\?
Anchors
This needs to specify match position.
Example
Description
^Python
Python$
\APython
Python\Z
\bPython\b
\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python?=!
Python?!!
Example
Description
R?#comment
R?iuby
R?i:uby
Same as above
rub?:y|le)
Copyright tutorialspoint.com
The Common Gateway Interface, or CGI, is a set of standards that define how information is
exchanged between the web server and a custom script. The CGI specs are currently maintained
by the NCSA and NCSA.
What is CGI?
The Common Gateway Interface, or CGI, is a standard for external gateway programs to
interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link to browse a
particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e., filename.
Web Server parses the URL and looks for the filename. If it finds that file then sends it back to
the browser, otherwise sends an error message indicating that you requested a wrong file.
Web browser takes response from web server and displays either the received file or error
message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is
requested that file is not sent back; instead it is executed as a program, and whatever that
program outputs is sent back for your browser to display. This function is called the Common
Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a
Python Script, PERL Script, Shell Script, C or C++ program, etc.
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.
"Content-type:text/html\r\n\r\n"
'<html>'
'<head>'
'<title>Hello Word - First CGI Program</title>'
'</head>'
'<body>'
'<h2>Hello Word! This is my first CGI program</h2>'
'</body>'
'</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 printed Contenttype:text/html\r\n\r\n. This line is sent back to the browser and it specifies the content type to be
displayed on the browser screen.
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 external system also to exchange
information such as RDBMS.
HTTP Header
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to
understand the content. All the HTTP header will be in the following form
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in your CGI
Programming.
Header
Description
Content-type:
Expires: Date
Location: URL
The URL that is returned instead of the URL requested. You can
use this field to redirect a request to any file.
Last-modified: Date
Content-length: N
The length, in bytes, of the data being returned. The browser uses
this value to report the estimated download time for a file.
Set-Cookie: String
Description
CONTENT_TYPE
The data type of the content. Used when the client is sending
attached content to the server. For example, file upload.
CONTENT_LENGTH
HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
HTTP_USER_AGENT
PATH_INFO
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
The fully qualified name of the host making the request. If this
information is not available, then REMOTE_ADDR can be used to
get IR address.
REQUEST_METHOD
SCRIPT_FILENAME
SCRIPT_NAME
SERVER_NAME
SERVER_SOFTWARE
Here is small CGI program to list out all the CGI variables. Click this link to see the result Get
Environment
#!/usr/bin/python
import os
print "Content-type: text/html\r\n\r\n";
print "<font size=+1>Environment</font><\br>";
for param in os.environ.keys():
print "<b>%20s</b>: %s<\br>" % (param, os.environ[param])
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
limtation: only 1024 characters can be sent in a request string. The GET method sends information
using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING
environment variable.
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.
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n"
"<html>"
"<head>"
"<title>Hello - Second CGI Program</title>"
"</head>"
"<body>"
"<h2>Hello %s %s</h2>" % (first_name, last_name)
"</body>"
"</html>"
Here is the actual output of the above form, you enter First and Last Name and then click submit
button to see the result.
First Name:
Last Name:
"Content-type:text/html\r\n\r\n"
"<html>"
"<head>"
"<title>Hello - Second CGI Program</title>"
"</head>"
"<body>"
"<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Let us take again same example as above which passes two values using HTML FORM and submit
button. We use same CGI script hello_get.py to handle this input.
<form action="/cgi-bin/hello_get.py" method="post">
First Name: <input type="text" name="first_name"><br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
Here is the actual output of the above form. You enter First and Last Name and then click submit
button to see the result.
First Name:
Last Name:
Physics
Below is checkbox.cgi script to handle input given by web browser for checkbox button.
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('maths'):
math_flag = "ON"
else:
math_flag = "OFF"
if form.getvalue('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF"
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n"
"<html>"
"<head>"
"<title>Checkbox - Third CGI Program</title>"
"</head>"
"<body>"
"<h2> CheckBox Maths is : %s</h2>" % math_flag
"<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"
Physics
Below is radiobutton.py script to handle input given by web browser for radio button:
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('subject'):
subject = form.getvalue('subject')
else:
subject = "Not set"
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n"
"<html>"
"<head>"
"<title>Radio - Fourth CGI Program</title>"
"</head>"
"<body>"
"<h2> Selected Subject is %s</h2>" % subject
"</body>"
"</html>"
"Content-type:text/html\r\n\r\n"
"<html>"
"<head>";
"<title>Text Area - Fifth CGI Program</title>"
"</head>"
"<body>"
"<h2> Entered Text Content is %s</h2>" % text_content
"</body>"
"Content-type:text/html\r\n\r\n"
"<html>"
"<head>"
"<title>Dropdown Box - Sixth CGI Program</title>"
"</head>"
"<body>"
"<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when
the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved,
your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that sets the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
Name=Value: Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before
to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the
cookies is done as follows
#!/usr/bin/python
print "Set-Cookie:UserID=XYZ;\r\n"
print "Set-Cookie:Password=XYZ123;\r\n"
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n"
print "Set-Cookie:Domain=www.tutorialspoint.com;\r\n"
print "Set-Cookie:Path=/perl;\n"
print "Content-type:text/html\r\n\r\n"
...........Rest of the HTML Content....
From this example, you must have understood how to set cookies. We use Set-Cookie HTTP
header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are
set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable
HTTP_COOKIE and they will have following form
key1=value1;key2=value2;key3=value3....
#!/usr/bin/python
# Import modules for CGI handling
from os import environ
import cgi, cgitb
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
print "User ID = %s" % user_id
print "Password = %s" % password
This produces the following result for the cookies set by above script
User ID = XYZ
Password = XYZ123
Above example has been disabled intentionally to save people uploading file on our server, but
you can try above code with your server.
Here is the script save_file.py to handle file upload
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
If you run the above script on Unix/Linux, then you need to take care of replacing file separator as
follows, otherwise on your windows machine above open statement should work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces
adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide
range of database servers such as
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
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.
The DB API provides a minimal standard for working with databases using Python structures and
syntax wherever possible. This API includes the following:
Importing the API module.
Acquiring a connection with the database.
Issuing SQL statements and stored procedures.
Closing the connection
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.
If it produces the following result, then it means MySQLdb module is not installed:
Traceback (most recent call last):
File "test.py", line 3, in <module>
import MySQLdb
To install MySQLdb module, download it from MySQLdb Download page and proceed as follows:
$
$
$
$
$
gunzip MySQL-python-1.2.2.tar.gz
tar -xvf MySQL-python-1.2.2.tar
cd MySQL-python-1.2.2
python setup.py build
python setup.py install
Note: Make sure you have root privilege to install above module.
Database Connection
Before connecting to a MySQL database, make sure of the followings
You have created a database TESTDB.
You have created a table EMPLOYEE in TESTDB.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
Python module MySQLdb is installed properly on your machine.
You have gone through MySQL tutorial to understand MySQL Basics.
Example
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data
# disconnect from server
db.close()
While running this script, it is producing the following result in my Linux machine.
Database version : 5.0.45
If a connection is established with the datasource, then a Connection Object is returned 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.
Example
Let us create Database table EMPLOYEE:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
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 into EMPLOYEE table
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Example
Following code segment is another form of execution where you can pass parameters directly
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % \
(user_id, 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 method to fetech multiple
values from a database table.
fetchone: It fetches the next row of a query result set. A result set is an object that is
returned when a cursor object is used to query a table.
fetchall: It fetches all the rows in a result set. If some rows have already been extracted
from the result set, then it retrieves the remaining rows from the result set.
rowcount: This is a read-only attribute and returns the number of rows that were affected
by an execute method.
Example
The following procedure queries all the records from EMPLOYEE table having salary more than
1000
#!/usr/bin/python
import MySQLdb
Update Operation
UPDATE Operation on any database means to update one or more records, which are already
available in the database.
The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all
the males by one year.
Example
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
DELETE Operation
DELETE operation is required when you want to delete some records from your database.
Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20
Example
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the following four
properties:
Atomicity: Either a transaction completes or nothing happens at all.
Consistency: A transaction must start in a consistent state and leave the system in a
consistent state.
Isolation: Intermediate results of a transaction are not visible outside the current
transaction.
Durability: Once a transaction was committed, the effects are persistent, even after a
system failure.
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
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
COMMIT Operation
Commit is the operation, which gives a green signal to database to finalize the changes, and after
this operation, no change can be reverted back.
Here is a simple example to call commit method.
db.commit()
ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back those changes
completely, then use rollback method.
Here is a simple example to call rollback method.
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 calling commit or rollback explicitly.
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 canceled or finished
statement handle.
The DB API defines a number of errors that must exist in each database module. The following
table lists these exceptions.
Exception
Description
Warning
Error
InterfaceError
Used for errors in the database module, not the database itself. Must
subclass Error.
DatabaseError
DataError
OperationalError
IntegrityError
InternalError
ProgrammingError
NotSupportedError
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 information about
them by reading the DB API 2.0 specification.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
Python provides two levels of access to network services. At a low level, you can access the basic
socket support in the underlying operating system, which allows you to implement clients and
servers for both connection-oriented and connectionless protocols.
Python also has libraries that provide higher-level access to specific application-level network
protocols, such as FTP, HTTP, and so on.
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 communicate
within a process, between processes on the same machine, or between processes on different
continents.
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.
Sockets have their own vocabulary:
Term
Description
domain
type
protocol
hostname
port
Each server listens for clients calling on one or more ports. A port may be a
Fixnum port number, a string containing a port number, or the name of a
service.
Description
s.bind
s.listen
s.accept
This passively accept TCP client connection, waiting until connection arrives
blocking.
Description
s.connect
Description
s.recv
s.send
s.recvfrom
s.sendto
s.close
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 bindhostname, 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 the connection to that
client.
#!/usr/bin/python
import socket
s = socket.socket()
# Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345
s.bind((host, port))
s.listen(5)
# Now wait for client connection.
while True:
c, addr = s.accept()
# Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
# Close the connection
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 socket module function.
The socket.connecthosname, port opens a TCP connection to hostname on the port. Once you have
a socket open, you can read from it like any IO object. When done, remember to close it, as you
would close a file.
The following code is a very simple client that connects to a given host and port, reads any
available data from the socket, and then exits
#!/usr/bin/python
import socket
s = socket.socket()
# Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345
# Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close
Now run this server.py in background and then run above client.py to see the result.
# Following would start a server in background.
$ python server.py &
# Once server is started run client as follows:
$ python client.py
Common function
Port No
Python module
HTTP
Web pages
80
NNTP
Usenet news
119
nntplib
FTP
File transfers
20
ftplib, urllib
SMTP
Sending email
25
smtplib
POP3
Fetching email
110
poplib
IMAP4
Fetching email
143
imaplib
Telnet
Command lines
23
telnetlib
Gopher
Document transfers
70
gopherlib, urllib
Please check all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP protocols.
Further Readings
This was a quick start with Socket Programming. It is a vast subject. It is recommended to go
through the following link to find more detail
Unix Socket Programming.
Python Socket Library and Modules.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
Simple Mail Transfer Protocol SMTP is a protocol, which handles sending e-mail and routing e-mail
between mail servers.
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 used to send an e-mail
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
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']
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
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, separated from the body
of the e-mail with a blank line.
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 eventhoughthefromandtoaddressesarewithinthee mailitself, thesearen talwaysusedtoroutemail.
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 a webmail service
suchasHotmailorYahoo!Mail, your e-mail provider must have provided you with outgoing mail server
details that you can supply them, as follows
smtplib.SMTP('mail.your-domain.com', 25)
Example
Following is the example to send HTML content as an e-mail. Try it once
#!/usr/bin/python
import smtplib
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Example
Following is the example, which sends a file /tmp/test.txt as an attachment. Try it once
#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
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)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%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"
Copyright tutorialspoint.com
Running several threads is similar to running several different programs concurrently, but with the
following benefits
Multiple threads within a process share the same data space with the main thread and can
therefore share information or communicate with each other more easily than if they were
separate processes.
Threads sometimes called light-weight processes and they do not require much memory
overhead; they care cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer
that keeps track of where within its context it is currently running.
It can be pre-empted interrupted
It can temporarily be put on hold alsoknownassleeping while other threads are running - this is
called yielding.
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 agrs. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any
arguments. kwargs is an optional dictionary of keyword arguments.
Example
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
Thread-1:
Thread-2:
Thread-1:
Thread-2:
Thread-1:
Thread-1:
Thread-2:
Thread-2:
Thread-2:
Thu
Thu
Thu
Thu
Thu
Thu
Thu
Thu
Thu
Jan
Jan
Jan
Jan
Jan
Jan
Jan
Jan
Jan
22
22
22
22
22
22
22
22
22
15:42:19
15:42:19
15:42:21
15:42:23
15:42:23
15:42:25
15:42:27
15:42:31
15:42:35
2009
2009
2009
2009
2009
2009
2009
2009
2009
Although it is very effective for low-level threading, but the thread module is very limited
compared to the newer threading module.
Example
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
09:10:03
09:10:04
09:10:04
09:10:05
09:10:06
09:10:06
09:10:07
2013
2013
2013
2013
2013
2013
2013
09:10:08 2013
09:10:10 2013
09:10:12 2013
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 Lock method, which
returns the new lock.
The acquireblocking method of the new lock object is used to force threads to run synchronously.
The optional blocking parameter enables you to control whether the thread waits to acquire the
lock.
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 blocks and wait for the lock
to be released.
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
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
09:11:28
09:11:29
09:11:30
09:11:32
09:11:34
09:11:36
2013
2013
2013
2013
2013
2013
Example
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
Starting Thread-2
Starting Thread-3
Thread-1 processing
Thread-2 processing
Thread-3 processing
Thread-1 processing
Thread-2 processing
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
One
Two
Three
Four
Five
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
XML is a portable, open source language that allows programmers to develop applications that
can be read by other applications, regardless of operating system and/or developmental
language.
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 requiring a
SQL-based backbone.
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
Example
#!/usr/bin/python
import xml.sax
class MovieHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
self.type = ""
self.format = ""
self.year = ""
self.rating = ""
self.stars = ""
self.description = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "movie":
print "*****Movie*****"
title = attributes["title"]
print "Title:", title
# Call when an elements ends
def endElement(self, tag):
if self.CurrentData == "type":
print "Type:", self.type
elif self.CurrentData == "format":
print "Format:", self.format
elif self.CurrentData == "year":
print "Year:", self.year
elif self.CurrentData == "rating":
print "Rating:", self.rating
elif self.CurrentData == "stars":
print "Stars:", self.stars
elif self.CurrentData == "description":
print "Description:", self.description
self.CurrentData = ""
# Call when a character is read
def characters(self, content):
if self.CurrentData == "type":
self.type = content
elif self.CurrentData == "format":
self.format = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "rating":
self.rating = content
elif self.CurrentData == "stars":
self.stars = content
elif self.CurrentData == "description":
self.description = content
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = MovieHandler()
parser.setContentHandler( Handler )
parser.parse("movies.xml")
For a complete detail on SAX API documentation, please refer to standard Python SAX APIs.
For a complete detail on DOM API documentation, please refer to standard Python DOM APIs.
Processing math: 72%
Copyright tutorialspoint.com
Python provides various options for developing graphical user interfaces GUIs. Most important are
listed below.
Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would
look this option in this chapter.
wxPython: This is an open-source Python interface for wxWindows http://wxpython.org.
JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java
class libraries on the local machine http://www.jython.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 object-oriented interface to
the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following
steps
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
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()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application.
These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief
description in the following table
Operator
Button
Description
The Button widget is used to display buttons in your application.
Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.
Checkbutton
Entry
The Entry widget is used to display a single-line text field for accepting values
from a user.
Frame
Label
Listbox
Menubutton
The Label widget is used to provide a single-line caption for other widgets. It
can also contain images.
The Listbox widget is used to provide a list of options to a user.
Menu
Message
The Message widget is used to display multiline text fields for accepting values
from a user.
Radiobutton
Scale
Scrollbar
Text
Toplevel
Spinbox
The Scrollbar widget is used to add scrolling capability to various widgets, such
as list boxes.
The Text widget is used to display text in multiple lines.
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can
be used to select from a fixed number of values.
PanedWindow
LabelFrame
tkMessageBox
Standard attributes
Let us take a look at how some of their common attributes.such as sizes, colors and fonts are
specified.
Dimensions
Colors
Fonts
Anchors
Relief styles
Bitmaps
Cursors
Let us study them briefly
Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have the
purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following
geometry manager classes: pack, grid, and place.
The pack Method - This geometry manager organizes widgets in blocks before placing them
in the parent widget.
The grid Method - This geometry manager organizes widgets in a table-like structure in the
parent widget.
The place Method -This geometry manager organizes widgets by placing them in a specific
position in the parent widget.
Let us study the geometry management methods briefly
Loading [MathJax]/jax/output/HTML-CSS/jax.js
Copyright tutorialspoint.com
Any code that you write using any compiled language like C, C++, or Java can be integrated or
imported into another Python script. This code is considered as an "extension."
A Python extension module is nothing more than a normal C library. On Unix machines, these
libraries usually end in .so forsharedobject. On Windows machines, you typically see .dll
fordynamicallylinkedlibrary.
The C Functions
The signatures of the C implementation of your functions always takes one of the following three
forms
static PyObject *MyFunction( PyObject *self, PyObject *args );
static PyObject *MyFunctionWithKeywords(PyObject *self,
PyObject *args,
PyObject *kw);
static PyObject *MyFunctionWithNoArgs( PyObject *self );
Each one of the preceding declarations returns a Python object. There is no such thing 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 macro, Py_RETURN_NONE, that
does this for us.
The names of your C functions can be whatever you like as they are never seen outside of the
extension module. They are defined as static function.
Your C functions usually are named by combining the Python module and function names
together, as shown here
static PyObject *module_func(PyObject *self, PyObject *args) {
/* Do your stuff here. */
Py_RETURN_NONE;
}
This is a Python function called func inside of the module module. You will be putting pointers to
your C functions into the method table for the module that usually comes next in your source code.
Example
For the above-defined function, we have following method mapping table
static PyMethodDef module_methods[] = {
{ "func", (PyCFunction)module_func, METH_NOARGS, NULL },
{ NULL, NULL, 0, NULL }
};
particular environment in which we're compiling. All you have to do is use it when defining the
function.
Your C initialization function generally has the following overall structure
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
Example
A simple example that makes use of all the above concepts
#include <Python.h>
static PyObject* helloworld(PyObject* self)
{
return Py_BuildValue("s", "Hello, Python extensions!!");
}
static char helloworld_docs[] =
"helloworld( ): Any message you want to put here!!\n";
static PyMethodDef helloworld_funcs[] = {
{"helloworld", (PyCFunction)helloworld,
METH_NOARGS, helloworld_docs},
{NULL}
};
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.
The distutils package makes it very easy to distribute Python modules, both pure 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
from distutils.core import setup, Extension
setup(name='helloworld', version='1.0', \
ext_modules=[Extension('helloworld', ['hello.c'])])
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
$ python setup.py install
On Unix-based systems, you'll most likely need to run this command as root in order to 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 call that extension in your
Python script as follows
#!/usr/bin/python
import helloworld
print helloworld.helloworld()
The method table containing an entry for the new function would look like this
static PyMethodDef module_methods[] = {
{ "func", (PyCFunction)module_func, METH_NOARGS, NULL },
{ "func", module_func, METH_VARARGS, NULL },
{ NULL, NULL, 0, NULL }
};
You can use API PyArg_ParseTuple function to extract the arguments from the one PyObject
pointer passed into your C function.
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 the format string as follows.
static PyObject *module_func(PyObject *self, PyObject *args) {
int i;
double d;
char *s;
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
module.func(1, s="three", d=2.0)
module.func(i=1, d=2.0, s="three")
module.func(s="three", d=2.0, i=1)
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 describes mandatory and
optional arguments.
Here is a list of format codes for PyArg_ParseTuple function
Code
C type
Meaning
char
double
float
int
long
long long
PyObject*
char*
s#
char*+int
t#
char*+int
Py_UNICODE*
u#
Py_UNICODE*+int
w#
char*+int
char*
z#
char*+int
...
as per ...
Returning Values
Py_BuildValue takes in a format string much like PyArg_ParseTuple does. Instead of passing in the
addresses of the values you are building, you pass in the actual values. Here's an example
showing how to implement an add function
static PyObject *foo_add(PyObject *self, PyObject *args) {
int a;
int b;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) {
return NULL;
}
return Py_BuildValue("i", a + b);
}
You can return two values from your function as follows, this would be cauptured using a list in
Python.
static PyObject *foo_add_subtract(PyObject *self, PyObject *args) {
int a;
int b;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) {
return NULL;
}
return Py_BuildValue("ii", a + b, a - b);
}
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* result is a new reference.
Following table lists the commonly used code strings, of which zero or more are joined into string
format.
Code
C type
Meaning
char
double
float
int
long
PyObject*
PyObject*
O&
convert+void*
Arbitrary conversion
char*
s#
char*+int
Py_UNICODE*
u#
Py_UNICODE*+int
w#
char*+int
char*
z#
char*+int
...
as per ...
[...]
as per ...
{...}
as per ...
Code {...} builds dictionaries from an even number of C values, alternately keys and values. For
example, Py_BuildValue " issi " , 23, " zig " , " zag " , 42 returns a dictionary like Python's
{23:'zig','zag':42}.
Processing math: 100%
Copyright tutorialspoint.com
PYTHON OVERVIEW:
Python is a high-level, interpreted, interactive and object oriented-scripting language.
Python is Interpreted
Python is Interactive
Python is Object-Oriented
Python is Beginner's Language
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's feature highlights include:
Easy-to-learn
Easy-to-read
Easy-to-maintain
A broad standard library
Interactive Mode
Portable
Extendable
Databases
GUI Programming
Scalable
GETTING PYTHON:
The most up-to-date and current source code, binaries, documentation, news, etc. is available at
the official website of Python:
Python Official Website : http://www.python.org/
You can download the Python documentation from the following site. The documentation is
available in HTML, PDF, and PostScript formats.
Python Documentation Website : www.python.org/doc/
Type the following text to the right of the Python prompt and press the Enter key:
>>> print "Hello, Python!";
PYTHON IDENTIFIERS:
A Python identifier is a name used to identify a variable, function, class, module, or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus Manpower and manpower are two different
identifiers in Python.
Here are following identifier naming convention for Python:
Class names start with an uppercase letter and all other identifiers with a lowercase letter.
Starting an identifier with a single leading underscore indicates by convention that the
identifier is meant to be private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
RESERVED WORDS:
The following list shows the reserved words in Python. These reserved words may not be used as
constant or variable or any other identifier names.
and
exec
not
assert
finally
or
break
for
pass
class
from
continue
global
raise
def
if
return
del
import
try
elif
in
while
else
is
with
except
lambda
yield
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. Both blocks in this example are fine:
if True:
print "True"
else:
print "False"
MULTI-LINE STATEMENTS:
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
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 can be used to span the string across multiple lines. For example, all the
following are legal:
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 physical line end are part of the comment, and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print "Hello, Python!";
# second comment
This is a comment.
This is a comment, too.
This is a comment, too.
I said that already.
Example:
if expression :
suite
elif expression :
suite
else :
suite
# An integer assignment
# A floating point
# A string
print counter
print miles
print name
PYTHON NUMBERS:
Number objects are created when you assign a value to them. For example:
var1 = 1
var2 = 10
long
float
complex
10
51924361L
0.0
3.14j
100
-0x19323L
15.20
45.j
-786
0122L
-21.9
9.322e-36j
080
0xDEFABCECBDAECBFBAEL
32.3+e18
.876j
-0490
535633629843L
-90.
-.6545+0J
-0x260
-052318172735L
-32.54e100
3e+26J
0x69
-4721885298529L
70.2-E12
4.53e-7j
PYTHON STRINGS:
Strings in Python are identified as a contiguous set of characters in between quotation marks.
Example:
str = 'Hello World!'
print str
print
print
print
print
print
str[0]
str[2:5]
str[2:]
str * 2
str + "TEST"
#
#
#
#
#
Prints
Prints
Prints
Prints
Prints
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 ([]).
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print
print
print
print
print
print
list
# Prints complete list
list[0]
# Prints first element of the list
list[1:3]
# Prints elements starting from 2nd to 4th
list[2:]
# Prints elements starting from 3rd element
tinylist * 2 # Prints list two times
list + tinylist # Prints concatenated lists
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.
Tuples can be thought of as read-only lists.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2
tinytuple = (123, 'john')
print
print
print
print
print
print
tuple
# Prints complete list
tuple[0]
# Prints first element of the list
tuple[1:3]
# Prints elements starting from 2nd to 4th
tuple[2:]
# Prints elements starting from 3rd element
tinytuple * 2
# Prints list two times
tuple + tinytuple # Prints concatenated lists
PYTHON DICTIONARY:
Python 's dictionaries are hash table type. They work like associative arrays or hashes found in Perl
and consist of key-value pairs.
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one']
# Prints value for 'one' key
print dict[2]
# Prints value for 2 key
print tinydict
# Prints complete dictionary
print tinydict.keys()
# Prints all the keys
print tinydict.values() # Prints all the values
Description
Example
a + b will give 30
b / a will give 2
b % a will give 0
**
//
==
(a == b) is not true.
!=
(a != b) is true.
<>
>
<
(a < b) is true.
>=
<=
(a <= b) is true.
+=
c += a is equivalent to c = c + a
-=
c -= a is equivalent to c = c - a
*=
c *= a is equivalent to c = c * a
/=
c /= a is equivalent to c = c / a
%=
c %= a is equivalent to c = c %
a
**=
c **= a is equivalent to c = c **
//=
c //= a is equivalent to c = c // a
&
<<
>>
and
(a and b) is true.
or
(a or b) is true.
not
in
x in y, here in results in a 1 if x
is a member of sequence y.
not in
is
is not
Description
**
~+-
+-
>> <<
&
Bitwise 'AND'
^|
Comparison operators
<> == !=
Equality operators
Assignment operators
is is not
Identity operators
in not in
Membership operators
note or and
Logical operators
THE IF STATEMENT:
The syntax of the if statement is:
if expression:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
# First Example
break
print 'Current Letter :', letter
var = 10
# Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
DEFINING A FUNCTION
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python:
Function blocks begin with the keyword def followed by the function name and parentheses (
( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior, and you need to inform them in the same order
that they were defined.
Example:
Here is the simplest form of a Python function. This function takes a string as input parameter and
prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
CALLING A FUNCTION
Defining a function only gives it a name, specifies the parameters that are to be included in the
function, and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt.
Following is the example to call printme() function:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
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, classes, and
variables. A module can also include runnable code.
Example:
The Python code for a module named aname normally resides in a file named aname.py. Here's
an example of a simple module, hello.py
def print_func( par ):
print "Hello : ", par
return
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches before
importing a module.
Example:
To import the module hello.py, you need to put the following command at the top of the script:
#!/usr/bin/python
# Import module hello
import hello
# Now you can call defined function that module as follows
hello.print_func("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.
Syntax:
file object = open(file_name [, access_mode][, buffering])
Description
Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer will be at the beginning of the
file.
rb+
Opens a file for both reading and writing in binary format. The file pointer will be at the
beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
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.
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.
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
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.
Attribute
Description
file.closed
file.mode
file.name
file.softspace
FILE POSITIONS:
The tell() method tells you the current position within the file in other words, the next read or write
will occur at that many bytes from the beginning of the file:
The seek(offset[, from]) method changes the current file position. The offset argument indicates
the number of bytes to be moved. The from argument specifies the reference position from where
the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use
the current position as the reference position and if it is set to 2 then the end of the file would be
taken as the reference position.
DIRECTORIES IN PYTHON:
Syntax:
os.mkdir("newdir")
Syntax:
os.chdir("newdir")
Syntax:
os.getcwd()
Syntax:
os.rmdir('dirname')
HANDLING AN EXCEPTION:
If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block. After the try: block, include an except: statement,
followed by a block of code which handles the problem as elegantly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:
try:
Do you operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above mentioned syntax:
A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
STANDARD EXCEPTIONS:
Here is a list standard Exceptions available in Python: Standard Exceptions
ARGUMENT OF AN EXCEPTION:
An exception can have an argument, which is a value that gives additional information about the
problem. The contents of the argument vary by exception. You capture an exception's argument
by supplying a variable in the except clause as follows:
try:
Do you operations here;
......................
except ExceptionType, Argument:
RAISING AN EXCEPTIONS:
You can raise exceptions in several ways by using the raise statement. The general syntax for the
raise statement.
Syntax:
raise [Exception [, args [, traceback]]]
USER-DEFINED EXCEPTIONS:
Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions.
Here is an example related to RuntimeError. Here a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e
is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise your exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
CREATING CLASSES:
The class statement creates a new class definition. The name of the class immediately follows the
keyword class followed by a colon as follows:
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string which can be access via ClassName.__doc__.
The class_suite consists of all the component statements, defining class members, data
attributes, and functions.
ACCESSING ATTRIBUTES:
You access the object's attributes using the dot operator with object. Class variable would be
CLASS INHERITANCE:
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by
listing the parent class in parentheses after the new class name:
The child class inherits the attributes of its parent class, and you can use those attributes as if they
were defined in the child class. A child class can also override data members and methods from
the parent.
Syntax:
Derived classes are declared much like their parent class; however, a list of base classes to inherit
from are given after the class name:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
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.
class Parent:
# define parent class
def myMethod(self):
# instance of child
# child calls overridden method
__del__( self )
Destructor, deletes an object
Sample Call : dell obj
__repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
__str__( self )
Printable string representation
Sample Call : str(obj)
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
OVERLOADING OPERATORS:
Suppose you've 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:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
DATA HIDING:
An object's attributes may or may not be visible outside the class definition. For these cases, you
can name attributes with a double underscore prefix, and those attributes will not be directly
visible to outsiders:
#!/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
A regular expression is a special sequence of characters that helps you match or find other strings
or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used
in UNIX world.
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'.
Description
pattern
string
flags
You can specifiy different flags using exclusive OR (|). These are
modifiers which are listed in the table below.
The re.match function returns a match object on success, None on failure. We would use
group(num) or groups() function of match object to get matched expression.
Match Object Methods
Description
group(num=0)
groups()
This function search for first occurrence of RE pattern within string with optional flags.
Here is the syntax for this function:
re.string(pattern, string, flags=0)
Description
pattern
string
flags
You can specifiy different flags using exclusive OR (|). These are
modifiers which are listed in the table below.
The re.search function returns a match object on success, None on failure. We would use
group(num) or groups() function of match object to get matched expression.
Match Object Methods
Description
group(num=0)
groups()
MATCHING VS SEARCHING:
Python offers two different primitive operations based on regular expressions: match checks for a
match only at the beginning of the string, while search checks for a match anywhere in the string
(this is what Perl does by default).
Syntax:
sub(pattern, repl, string, max=0)
This method replace all occurrences of the RE pattern in string with repl, substituting all
occurrences unless max provided. This method would return modified string.
Description
re.I
re.L
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).
re.S
re.U
Interprets letters according to the Unicode character set. This flag affects the
behavior of \w, \W, \b, \B.
re.X
Permits "cuter" regular expression syntax. It ignores whitespace (except inside a set
[] or when escaped by a backslash), and treats unescaped # as a comment marker.
REGULAR-EXPRESSION PATTERNS:
Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You
can escape a control character by preceding it with a backslash.
Following table lists the regular expression syntax that is available in Python.
Pattern
Description
[...]
[^...]
re*
re+
re{ n}
re{ n,}
re{ n, m}
a| b
Matches either a or b.
(re)
(?imx)
(?-imx)
(?: re)
(?imx: re)
(?-imx: re)
(?#...)
Comment.
(?= re)
(?! re)
(?> re)
\w
\W
\s
\S
Matches nonwhitespace.
\d
\D
Matches nondigits.
\A
\Z
\z
\G
\b
\B
\1...\9
\10
REGULAR-EXPRESSION EXAMPLES:
Literal characters:
Example
Description
python
Match "python".
Character classes:
Example
Description
[Pp]ython
rub[ye]
[aeiou]
[0-9]
[a-z]
[A-Z]
[a-zA-Z0-9]
[^aeiou]
[^0-9]
Description
\d
\D
\s
\S
\w
\W
Repetition Cases:
Example
Description
ruby?
ruby*
ruby+
\d{3}
\d{3,}
\d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition:
This matches the smallest number of repetitions:
Example
Description
<.*>
<.*?>
No group: + repeats \d
(\D\d)+
([Pp]ython(, )?)+
Backreferences:
This matches a previously matched group again:
Example
Description
([Pp])ython&\1ails
(['"])[^\1]*\1
Alternatives:
Example
Description
python|perl
rub(y|le))
Python(!+|\?)
Anchors:
This need to specify match position
Example
Description
^Python
Python$
\APython
Python\Z
\bPython\b
\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python(?=!)
Python(?!!)
R(?i)uby
R(?i:uby)
Same as above
rub(?:y|le))
PYTHON TOOLS/UTILITIES
http://www.tutorialspoint.com/python/python_tools_utilities.htm
Copyright tutorialspoint.com
The standard library comes with a number of modules that can be used both as modules and as
command-line utilities.
Example
#!/usr/bin/python
import dis
def sum():
vara = 10
varb = 20
sum = vara + varb
print "vara + varb = %d" % sum
# Call dis function for the function.
dis.dis(sum)
0 LOAD_CONST
3 STORE_FAST
1 (10)
0 (vara)
6 LOAD_CONST
9 STORE_FAST
2 (20)
1 (varb)
10
12
15
18
19
LOAD_FAST
LOAD_FAST
BINARY_ADD
STORE_FAST
0 (vara)
1 (varb)
22
25
28
29
30
31
34
LOAD_CONST
LOAD_FAST
BINARY_MODULO
PRINT_ITEM
PRINT_NEWLINE
LOAD_CONST
RETURN_VALUE
2 (sum)
0 (None)
Example:
Before you try to run pdb.py, set your path properly to Python lib directory. So let us try with above
example sum.py
$pdb.py sum.py
> /test/sum.py(3)<module>()
-> import dis
(Pdb) n
> /test/sum.py(5)<module>()
-> def sum():
(Pdb) n
>/test/sum.py(14)<module>()
-> dis.dis(sum)
(Pdb) n
6
0 LOAD_CONST
3 STORE_FAST
7
1 (10)
0 (vara)
6 LOAD_CONST
9 STORE_FAST
10
2 (20)
1 (varb)
12
15
18
19
LOAD_FAST
LOAD_FAST
BINARY_ADD
STORE_FAST
0 (vara)
1 (varb)
22
25
28
29
30
31
34
LOAD_CONST
LOAD_FAST
BINARY_MODULO
PRINT_ITEM
PRINT_NEWLINE
LOAD_CONST
RETURN_VALUE
2 (sum)
0 (None)
--Return-> /test/sum.py(14)<module>()->None
-v dis.dis(sum)
(Pdb) n
--Return-> <string>(1)<module>()->None
(Pdb)
Example
Let us try to profile the following program
#!/usr/bin/python
vara = 10
varb = 20
sum = vara + varb
print "vara + varb = %d" % sum
tottime
0.000
0.000
0.000
0.000
percall
0.000
0.000
0.000
0.000
cumtime
0.000
0.000
0.000
0.000
percall filename:lineno
0.000 <string>:1(<module>)
0.000 sum.py:3(<module>)
0.000 {execfile}
0.000 {method ......}
Example
Let us try to profile the following program
#!/usr/bin/python
vara = 10
varb = 20
sum = vara + varb
print "vara + varb = %d" % sum
If you would try a correct file with tabnanny.py, then it won't complain as follows
$tabnanny.py -v sum.py
'sum.py': Clean bill of health.
Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js
Copyright tutorialspoint.com
The following resources contain additional information on Python Please use them to get more indepth knowledge on this topic.