Tutorialspoint Python
Tutorialspoint Python
com
hays://www.fac•6ook.com/tutorislspointlndis https://twitter.com/tutorlalspolnt
Python
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.
All the content and graphics published in this e-book are the property of Tutorials
Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial. If
you discover any errors on our website or in this tutorial, please notify us at
[email protected].
i
Python
Table of Contents
About the Tutorial....................................................................................................................................... i
Audience..................................................................................................................................................... i
Prerequisites............................................................................................................................................... i
Table of Contents....................................................................................................................................... ii
1. PYTHON ─ OVERVIEW........................................................................................................1
History of Python........................................................................................................................................ 1
Python Features......................................................................................................................................... 1
2. PYTHON ─ ENVIRONMENT................................................................................................3
Getting Python........................................................................................................................................... 3
Installing Python......................................................................................................................................... 4
Setting up PATH.......................................................................................................................................... 5
Running Python.......................................................................................................................................... 6
Python Identifiers..................................................................................................................................... 10
Python Keywords...................................................................................................................................... 11
Multi-Line Statements.............................................................................................................................. 13
ii
Python
Quotation in Python................................................................................................................................. 13
Comments in Python................................................................................................................................ 14
getopt.getopt method.............................................................................................................................. 17
Exception getopt.GetoptError................................................................................................................... 17
Multiple Assignment................................................................................................................................. 21
Python Numbers....................................................................................................................................... 21
Python Strings.......................................................................................................................................... 23
Python Lists.............................................................................................................................................. 24
Python Tuples........................................................................................................................................... 24
Python Dictionary..................................................................................................................................... 26
Types of Operators................................................................................................................................... 29
iii
Python
Python Assignment Operators.................................................................................................................. 34
If Statement............................................................................................................................................. 45
If…else Statement..................................................................................................................................... 46
7. PYTHON ─ LOOPS...............................................................................................................51
While Loop............................................................................................................................................... 52
For Loop................................................................................................................................................... 56
Nested Loops............................................................................................................................................ 59
Break Statement....................................................................................................................................... 61
Continue Statement.................................................................................................................................. 63
Pass Statement......................................................................................................................................... 65
8. PYTHON ─ NUMBERS........................................................................................................66
iv
Python
Number Type Conversion.......................................................................................................................... 67
Trigonometric Functions........................................................................................................................... 69
Mathematical Constants........................................................................................................................... 70
9. PYTHON ─ STRINGS...........................................................................................................71
Updating Strings....................................................................................................................................... 71
Escape Characters..................................................................................................................................... 72
Triple Quotes............................................................................................................................................ 76
Unicode String.......................................................................................................................................... 77
capitalize() Method................................................................................................................................... 82
decode(encoding='UTF-8',errors='strict') Method......................................................................................84
encode(encoding='UTF-8',errors='strict') Method......................................................................................85
expandtabs(tabsize=8).............................................................................................................................. 87
isalnum() Method..................................................................................................................................... 90
isalpha()................................................................................................................................................... 90
isdigit()..................................................................................................................................................... 91
islower()................................................................................................................................................... 92
v
Python
isnumeric()............................................................................................................................................... 93
isspace() Method...................................................................................................................................... 94
istitle()...................................................................................................................................................... 95
isupper()................................................................................................................................................... 96
join(seq)................................................................................................................................................... 96
len(string)................................................................................................................................................. 97
ljust(width[, fillchar])................................................................................................................................ 98
lower()..................................................................................................................................................... 99
lstrip().................................................................................................................................................... 100
maketrans()............................................................................................................................................ 100
max(str).................................................................................................................................................. 102
min(str).................................................................................................................................................. 102
rstrip().................................................................................................................................................... 107
splitlines(num=string.count('\n'))............................................................................................................ 109
strip([chars])........................................................................................................................................... 111
swapcase().............................................................................................................................................. 111
title()...................................................................................................................................................... 112
upper()................................................................................................................................................... 114
vi
Python
isdecimal().............................................................................................................................................. 116
len(List).................................................................................................................................................. 123
max(list)................................................................................................................................................. 124
min(list).................................................................................................................................................. 124
List.append(obj)...................................................................................................................................... 126
list.count(obj)......................................................................................................................................... 127
list.extend(seq)....................................................................................................................................... 128
list.index(obj)......................................................................................................................................... 128
list.insert(index,obj)................................................................................................................................ 129
list.pop(obj=list[-1])................................................................................................................................ 130
List.remove(obj)..................................................................................................................................... 131
List.reverse()........................................................................................................................................... 131
list.sort([func])........................................................................................................................................ 132
vii
Python
Basic Tuples Operations.......................................................................................................................... 136
Len(tuple)............................................................................................................................................... 139
Max(tuple).............................................................................................................................................. 140
Min(tuple).............................................................................................................................................. 141
Tuple(seg)............................................................................................................................................... 141
len(dict).................................................................................................................................................. 147
str(dict)................................................................................................................................................... 148
type()..................................................................................................................................................... 149
dict.clear().............................................................................................................................................. 151
Dict.copy().............................................................................................................................................. 151
Dict.fromkeys()....................................................................................................................................... 152
Dict.get(key,default=none)..................................................................................................................... 153
Dict.has_key(key)................................................................................................................................... 154
Dict.items()............................................................................................................................................. 155
Dict.keys().............................................................................................................................................. 156
viii
Python
dict.setdefault(key, default=None).......................................................................................................... 156
dict.update(dict2)................................................................................................................................... 157
dict.values()............................................................................................................................................ 158
time.altzone........................................................................................................................................... 165
time.actime([tupletime])........................................................................................................................ 166
time.ctime([secs])................................................................................................................................... 168
time.gmtime([secs])................................................................................................................................ 168
time.localtime([secs])............................................................................................................................. 169
time.mktime(tupletime)......................................................................................................................... 170
time.sleep(secs)...................................................................................................................................... 171
time.strftime(fmt[,tupletime])................................................................................................................ 172
time.tzset()............................................................................................................................................. 177
ix
Python
Defining a Function................................................................................................................................. 182
x
Python
Reading Keyboard Input.......................................................................................................................... 198
file.close()............................................................................................................................................... 210
File.flush().............................................................................................................................................. 211
File.fileno()............................................................................................................................................. 212
File.isatty().............................................................................................................................................. 213
File.next()............................................................................................................................................... 214
File.read([size])....................................................................................................................................... 215
xi
Python
File.readline([size])................................................................................................................................. 216
file.readline([sizehint])............................................................................................................................ 218
file.seek(offset[,whence])....................................................................................................................... 219
file.tell().................................................................................................................................................. 221
file.truncate([size])................................................................................................................................. 222
file.write(str).......................................................................................................................................... 224
file.writelines(sequence)......................................................................................................................... 225
xii
Python
Class Inheritance..................................................................................................................................... 251
Backreferences....................................................................................................................................... 267
xiii
Python
Simple URL Example : Get Method.......................................................................................................... 276
xiv
Python
Handling Errors....................................................................................................................................... 300
xv
Python
The parse Method.................................................................................................................................. 325
Button.................................................................................................................................................... 335
Canvas.................................................................................................................................................... 338
Checkbutton........................................................................................................................................... 340
Entry....................................................................................................................................................... 344
Frame..................................................................................................................................................... 349
Label....................................................................................................................................................... 351
Listbox.................................................................................................................................................... 354
MenuButton........................................................................................................................................... 358
Menu...................................................................................................................................................... 362
Message................................................................................................................................................. 366
Radiobutton........................................................................................................................................... 369
Scale....................................................................................................................................................... 373
Scrollbar................................................................................................................................................. 378
Text........................................................................................................................................................ 381
TopLevel................................................................................................................................................. 387
SpinBox.................................................................................................................................................. 390
PanelWindow......................................................................................................................................... 393
LabelFrame............................................................................................................................................. 396
tkMessageBox........................................................................................................................................ 398
xvi
Python
Dimensions............................................................................................................................................. 400
Colors..................................................................................................................................................... 401
Fonts...................................................................................................................................................... 402
Anchors.................................................................................................................................................. 403
Bitmaps.................................................................................................................................................. 406
Cursors................................................................................................................................................... 407
xvi
1.Python ─ Overview Pyth
Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
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, 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.
1
Python
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.
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 provides very high-level dynamic data types and supports dynamic type
checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
2
2.Python ─ Environment Pyth
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.
3
Pyth
Installing Python
Python distribution is available for a wide variety of platforms. You need to
download only the binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to
compile the source code manually. Compiling the source code offers more flexibility
in terms of choice of features that you require in your installation.
Windows Installation
Here are the steps to install Python on Windows machine.
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.
4
Pyth
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date.
See http://www.python.org/download/mac/ for instructions on getting the current
version along with extra tools to support development on the Mac. For older Mac
OS's before Mac OS X 10.3 (released in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation
at his website - http://www.cwi.nl/~jack/macpython.html. You can find complete installation
details for Mac OS installation.
The path variable is named as PATH in Unix or Path in Windows (Unix is case-
sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter
from any particular directory, you must add the Python directory to your path.
5
Pyth
Variable Description
Running Python
There are three different ways to start Python:
6
Pyth
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
Option Description
7
Pyth
Windows: PythonWin is the first Windows interface for Python and is an IDE
with a GUI.
Macintosh: The Macintosh version of Python along with the IDLE IDE is
available from the main website, downloadable as either MacBinary or
BinHex'd files.
If you are not able to set up the environment properly, then you can take help from
your system admin. Make sure the Python environment is properly set up and
working perfectly fine.
Note: All the examples given in subsequent chapters are executed with Python
2.4.3 version available on CentOS flavor of Linux.
We already have set up Python Programming environment online, so that you can
execute all the available examples online at the same time when you are learning
theory. Feel free to modify any example and execute it online.
8
3.Python ─ Basic Syntax Pyth
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:
If you are running new version of Python, then you 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!
Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file:
9
Pyth
We assume that you have Python interpreter set in PATH variable. Now, try to run
this program as follows:
$ python test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file:
#!/usr/bin/python
print "Hello, Python!";
We assume that you have Python interpreter available in /usr/bin directory. Now,
try to run this program as follows:
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).
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
1
Pyth
If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Python Keywords
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.
Assert finally or
def if return
elif in while
else is with
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example:
1
Pyth
if True:
print "True"
else:
print "False"
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of 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
1
Pyth
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:
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.
1
Pyth
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
Hello, Python!
You can type a comment on the same line after a statement or expression:
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
1
Pyth
#!/usr/bin/python
raw_input("\n\nPress the enter key to exit.")
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.
Header lines begin the statement (with the keyword) and terminate with a colon (:)
and are followed by one or more lines which make up the suite. For example:
if expression :
suite
elif expression :
suite
else :
suite
$ python -h
1
Pyth
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
You can also program your script in such a way that it should accept various options.
The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes:
Example
Consider the following script test.py:
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
1
Pyth
NOTE: As mentioned above, first argument is always script name and it is also
being counted in number of arguments.
getopt.getopt method
This method parses command line options and parameter list. Following is simple
syntax for this method:
options: This is the string of option letters that the script wants to
recognize, with options that require an argument should be followed by a
colon (:).
This method returns value consisting of two elements: the first is a list
of (option, value) pairs. The second is the list of program arguments left
after the option list was stripped.
Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long
options (e.g., '--long-option').
Exception getopt.GetoptEr or
This is raised when an unrecognized option is found in the argument list or when an
option requiring an argument is given none.
1
Pyth
The argument to the exception is a string indicating the cause of the error. The
attributes msg and opt give the error message and related option.
Example
Consider we want to pass two file names through command line and we also want to
give an option to check the usage of the script. Usage of the script is as follows:
#!/usr/bin/python
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile
1
Pyth
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile
Input file is " inputfile
Output file is "
1
4.Python ─ Variable Types Pyth
Variables are nothing but reserved memory locations to store values. This means
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.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example:
#!/usr/bin/python
print counter
print miles
print name
Here, 100, 1000.0, and "John" are the values assigned to counter, miles, and name
variables respectively. This produces the following result:
100
1000.0
John
2
Pyth
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.
Numbers
String
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:
2
Pyth
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:
2
Pyth
Python allows you to use a lowercase L with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1. Python
displays long integers with an uppercase L.
Python Strings
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
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
2
Pyth
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
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
2
Pyth
#!/usr/bin/python
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists:
#!/usr/bin/python
2
Pyth
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 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
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
2
Pyth
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
Function Description
2
Pyth
2
5.Python ─ Basic Operators Pyth
Operators are the constructs which can manipulate the value of operands.
Types of Operators
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
2
Pyth
Example
Assume variable a holds 10 and variable b holds 20, then:
#!/usr/bin/python
a = 21
b = 10
c = 0
c = a + b
print "Line 1 - Value of c is ", c
c = a - b
print "Line 2 - Value of c is ", c
c = a * b
print "Line 3 - Value of c is ", c
c = a / b
print "Line 4 - Value of c is ", c
c = a % b
print "Line 5 - Value of c is ", c
a = 2
b = 3
c = a**b
print "Line 6 - Value of c is ", c
3
Pyth
a = 10
b = 5
c = a//b
print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
3
Pyth
Example
Assume variable a holds 10 and variable b holds 20, then:
#!/usr/bin/python
a = 21
b = 10
c = 0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
3
Pyth
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
When you execute the above program it produces the following result:
3
Pyth
3
Pyth
Example
Assume variable a holds 10 and variable b holds 20, then:
#!/usr/bin/python
a = 21
b = 10
c = 0
c = a + b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c = 2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
3
Pyth
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
a = 0011 1100
b = 0000 1101
~a = 1100 0011
3
Pyth
Example
#!/usr/bin/python
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
3
Pyth
When you execute the above program it produces the following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
not Used to reverse the logical state of its Not (a and b) is false.
operand.
Logical NOT
3
Pyth
Example
#!/usr/bin/python
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"
a = 2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
When you execute the above program it produces the following result:
3
Pyth
Example
#!/usr/bin/python
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"
4
Pyth
if ( a is not b ):
print "Line 4 - a and b do not have same identity"
else:
print "Line 4 - a and b have same identity"
When you execute the above program it produces the following result:
Operator Description
4
Pyth
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom.
Example
#!/usr/bin/python
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
4
Pyth
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result:
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
4
6.Python ─ Decision Making Pyth
Following is the general form of a typical decision making structure found in most of
the programming languages:
Statement Description
4
Pyth
nested if You can use one if or else if statement inside another if or else
statements if statement(s).
If Statement
It is similar to that of other languages. The if statement contains a logical
expression using which data is compared and a decision is made based on the
result of the comparison.
Syntax
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. If boolean expression evaluates to FALSE, then the
first set of code after the end of the if statement(s) is executed.
Flow Diagram
4
Pyth
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
If…else Statement
An else statement can be combined with an if statement. An else statement
contains the block of code that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax
The syntax of the if...else statement is:
if expression:
statement(s)
else:
statement(s)
4
Pyth
Flow Diagram
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
4
Pyth
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
Similar to the else, the elif statement is optional. However, unlike else, for which
there can be at most one statement, there can be an arbitrary number
of elif statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but
we can use if..elif...statements to simulate switch case as follows:
4
Pyth
Example
#!/usr/bin/python
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
4
Pyth
#!/usr/bin/python
var = 100
5
7.Python ─ Loops Pyth
Programming languages provide various control structures that allow for more
complicated execution paths.
You can use one or more loop inside any another while, for or do..while
nested loops
loop.
5
Pyth
While Loop
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is:
while expression:
statement(s)
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single block of code.
Python uses indentation as its method of grouping statements.
Flow Diagram
5
Pyth
Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed.
Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
The block here, consisting of the print and increment statements, is executed
repeatedly until count is no longer less than 9. With each iteration, the current
value of the index count is displayed and then increased by 1.
5
Pyth
#!/usr/bin/python
var = 1
while var == 1 : # This constructs an infinite
loop num = raw_input("Enter a number :")
print "You entered: ", num
Above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.
5
Pyth
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise else
statement gets executed.
#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
#!/usr/bin/python
flag = 1
It is better not try above example because it goes into infinite loop and you need to
press CTRL+C keys to exit.
5
Pyth
For Loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterating_var. Next, the
statements block is executed. Each item in the list is assigned to iterating_var, and
the statement(s) block is executed until the entire sequence is exhausted.
Flow Diagram
Example
#!/usr/bin/python
5
Pyth
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
#!/usr/bin/python
5
Pyth
Here, we took the assistance of the len() built-in function, which provides the total
number of elements in the tuple as well as the range() built-in function to give us
the actual sequence to iterate over.
If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.
The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 through 20.
#!/usr/bin/python
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
5
Pyth
Nested Loops
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is
as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other
type of loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to
100:
#!/usr/bin/python
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1
5
Pyth
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
Python supports the following control statements. Click the following links to check
their detail.
6
Pyth
Control
Description
Statement
continue Causes the loop to skip the remainder of its body and
statement immediately retest its condition prior to reiterating.
Break Statement
It terminates the current loop and resumes execution at the next statement, just
like the traditional break statement in C.
The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in
both while and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax
The syntax for a break statement in Python is as follows:
break
6
Pyth
Flow Diagram
Example
#!/usr/bin/python
6
Pyth
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
Continue Statement
It returns the control to the beginning of the while loop. The continue statement
rejects all the remaining statements in the current iteration of the loop and moves
the control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
6
Pyth
Example
#!/usr/bin/python
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
6
Pyth
Pass Statement
It is used when a statement is required syntactically but you do not want any
command or code to execute.
Syntax
pass
Example
#!/usr/bin/python
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
6
8.Python ─ Numbers Pyth
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:
You can delete a single object or multiple objects by using the del statement. For
example:
del var
del var_a, var_b
int (signed integers): They are often called just integers or ints, are
positive or negative whole numbers with no decimal point.
long (long integers): Also called longs, they are integers of unlimited size,
written like integers and followed by an uppercase or lowercase L.
float (floating point real values) : Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and
fractional parts. Floats may also be in scientific notation, with E or e
indicating the power of 10 (2.5e2 = 2.5 x 10 2 = 250).
complex (complex numbers) : are of the form a + bJ, where a and b are
floats and J (or j) represents the square root of -1 (which is an imaginary
number). The real part of the number is a, and the imaginary part is b.
Complex numbers are not used much in Python programming.
6
Pyth
Examples
Here are some examples of numbers:
Python allows you to use a lowercase L with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1. Python
displays long integers with an uppercase L.
6
Pyth
Mathematical Functions
Python includes following functions that perform mathematical calculations.
abs(x) The absolute value of x: the (positive) distance between x and zero.
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
The fractional and integer parts of x in a two-item tuple. Both parts have
modf(x)
the same sign as x. The integer part is returned as a float.
x rounded to n digits from the decimal point. Python rounds away from
round(x [,n])
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
6
Pyth
Function Description
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
Function Description
6
Pyth
Mathematical Constants
The module also defines two mathematical constants:
Constants Description
7
9.Python ─ Strings Pyth
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:
To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring. For example:
#!/usr/bin/python
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string.
The new value can be related to its previous value or to a completely different
string altogether. For example:
#!/usr/bin/python
7
Pyth
Escape Characters
Following table is a list of escape or non-printable characters that can be
represented with backslash notation.
Backslash Hexadecimal
Description
notation character
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
72
Pyth
\t 0x09 Tab
\x Character x
73
Pyth
#!/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 %:
%c character
%o octal integer
74
Pyth
Other supported symbols and functionality are listed in the following table:
Symbol Functionality
- left justification
75
Pyth
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
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):
76
Pyth
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'
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as
follows:
#!/usr/bin/python
print r'C:\\nowhere'
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings
are stored as 16-bit Unicode. This allows for a more varied set of characters,
including special characters from most languages in the world. I'll restrict my
treatment of Unicode strings to the following:
#!/usr/bin/python
print u'Hello, world!'
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
77
Pyth
capitalize()
1
Capitalizes first letter of string.
center(width, fillchar)
2 Returns a space-padded string with the original string centered to a
total of width columns.
decode(encoding='UTF-8',errors='strict')
4 Decodes the string using the codec registered for encoding. encoding
defaults to the default string encoding.
encode(encoding='UTF-8',errors='strict')
5 Returns encoded string version of string; on error, default is to raise a
ValueError unless errors is given with 'ignore' or 'replace'.
expandtabs(tabsize=8)
7 Expands tabs in string to multiple spaces; defaults to 8 spaces per tab
if tabsize not provided.
78
Pyth
isalnum()
10 Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
isalpha()
11 Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
isdigit()
12
Returns true if string contains only digits and false otherwise.
islower()
13 Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
isnumeric()
14 Returns true if a unicode string contains only numeric characters and
false otherwise.
isspace()
15 Returns true if string contains only whitespace characters and false
otherwise.
istitle()
16
Returns true if string is properly "titlecased" and false otherwise.
isupper()
17 Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
join(seq)
18 Merges (concatenates) the string representations of elements in
sequence seq into a string, with separator string.
len(string)
19
Returns the length of the string.
79
Pyth
ljust(width[, fillchar])
20 Returns a space-padded string with the original string left-justified to a
total of width columns.
lower()
21
Converts all uppercase letters in string to lowercase.
lstrip()
22
Removes all leading whitespace in string.
maketrans()
23
Returns a translation table to be used in translate function.
max(str)
24
Returns the max alphabetical character from the string str.
min(str)
25
Returns the min alphabetical character from the string str.
rfind(str, beg=0,end=len(string))
27
Same as find(), but search backwards in string.
rjust(width,[, fillchar])
29 Returns a space-padded string with the original string right-justified to
a total of width columns.
rstrip()
30
Removes all trailing whitespace of string.
80
Pyth
split(str="", num=string.count(str))
31 Splits string according to delimiter str (space if not provided) and
returns list of substrings; split into at most num substrings if given.
splitlines( num=string.count('\n'))
32 Splits string at all (or num) NEWLINEs and returns a list of each line
with NEWLINEs removed.
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and
33
ending index end are given) starts with substring str; returns true if so
and false otherwise.
strip([chars])
34
Performs both lstrip() and rstrip() on string.
swapcase()
35
Inverts case for all letters in string.
title()
36 Returns "titlecased" version of string, that is, all words begin with
uppercase and the rest are lowercase.
translate(table, deletechars="")
37 Translates string according to translation table str(256 chars),
removing those in the del string.
upper()
38
Converts lowercase letters in string to uppercase.
zfill (width)
Returns original string leftpadded with zeros to a total of width
39
characters; intended for numbers, zfill() retains any sign given (less
one zero).
isdecimal()
40 Returns true if a unicode string contains only decimal characters and
false otherwise.
81
Pyth
capitalize() Method
It returns a copy of the string with only its first character capitalized.
Syntax
str.capitalize()
Parameters
NA
Return Value
string
Example
#!/usr/bin/python
Result
str.capitalize() : This is string example.. .wow!!!
Syntax
str.center(width[, fillchar])
Parameters
width -- This is the total width of the string.
fillchar -- This is the filler character.
82
Pyth
Return Value
This method returns centered in a string of length width.
Example
#!/usr/bin/python
Result
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa
Syntax
str.count(sub, start= 0,end=len(string))
Parameters
sub -- This is the substring to be searched.
start -- Search starts from this index. First character starts from 0 index. By
default search starts from 0 index.
end -- Search ends from this index. First character starts from 0 index. By
default search ends at the last index.
Return Value
Centered in a string of length width.
Example
#!/usr/bin/python
83
Pyth
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
Result
str.count(sub, 4, 40) : 2
str.count(sub, 4, 40) : 1
decode(encoding='UTF-8',errors='strict') Method
The method decode() decodes the string using the codec registered for encoding. It
defaults to the default string encoding.
Syntax
str.decode(encoding='UTF-8',errors='strict')
Parameters
encoding -- This is the encodings to be used. For a list of all encoding
schemes please visit: Standard Encodings.
errors -- This may be given to set a different error handling scheme. The
default for errors is 'strict', meaning that encoding errors raise a
UnicodeError. Other possible values are 'ignore', 'replace',
'xmlcharrefreplace', 'backslashreplace' and any other name registered via
codecs.register_error().
Return Value
Decoded string.
Example
#!/usr/bin/python
84
Pyth
Result
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
Decoded String: this is string example....wow!!!
encode(encoding='UTF-8',errors='strict') Method
The method encode() returns an encoded version of the string. Default encoding is
the current default string encoding. The errors may be given to set a different error
handling scheme.
Syntax
str.encode(encoding='UTF-8',errors='strict')
Parameters
encoding -- This is the encodings to be used. For a list of all encoding
schemes please visit Standard Encodings.
errors -- This may be given to set a different error handling scheme. The
default for errors is 'strict', meaning that encoding errors raise a
UnicodeError. Other possible values are 'ignore', 'replace',
'xmlcharrefreplace', 'backslashreplace' and any other name registered via
codecs.register_error().
Return Value
Encoded string.
Example
#!/usr/bin/python
str = "this is string example.. .wow!!!";
print "Encoded String: " + str.encode('base64','strict')
Result
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
85
Pyth
Syntax
str.endswith(suffix[, start[, end]])
Parameters
suffix -- This could be a string or could also be a tuple of suffixes to look for.
start -- The slice begins from here.
end -- The slice ends here.
Return Value
TRUE if the string ends with the specified suffix, otherwise FALSE.
Example
#!/usr/bin/python
suffix = "wow!!!";
print str.endswith(suffix);
print str.endswith(suffix,20);
suffix = "is";
print str.endswith(suffix, 2, 4);
print str.endswith(suffix, 2, 6);
Result
True
True
True
False
86
Pyth
expandtabs(tabsize=8)
It returns a copy of the string in which tab characters ie. '\t' are expanded using
spaces, optionally using the given tabsize (default 8).
Syntax
str.expandtabs(tabsize=8)
Parameters
tabsize -- This specifies the number of characters to be replaced for a tab
character '\t'.
Return Value
This method returns a copy of the string in which tab characters i.e., '\t' have
been expanded using spaces.
Example
#!/usr/bin/python
Result
Original string: this is string example....wow!!!
Defualt exapanded tab: this is string example....wow!!!
Double exapanded tab: this is string example....wow!!!
87
Pyth
Syntax
str.find(str, beg=0 end=len(string))
Parameters
str -- This specifies the string to be searched.
beg -- This is the starting index, by default its 0.
end -- This is the ending index, by default its equal to the lenght of the string.
Return Value
Index if found and -1 otherwise.
Example
The following example shows the usage of find() method.
#!/usr/bin/python
print str1.find(str2);
print str1.find(str2, 10);
print str1.find(str2, 40);
Result
15
15
-1
88
Pyth
Syntax
str.index(str, beg=0 end=len(string))
Parameters
str -- This specifies the string to be searched.
beg -- This is the starting index, by default its 0.
end -- This is the ending index, by default its equal to the length of the string.
Return Value
Index if found otherwise raises an exception if str is not found.
Example
#!/usr/bin/python
print str1.index(str2);
print str1.index(str2, 10);
print str1.index(str2, 40);
Result
15
15
Traceback (most recent call last):
File "test.py", line 8, in
print str1.index(str2, 40);
ValueError: substring not found
shell returned 1
89
Pyth
isalnum() Method
It checks whether the string consists of alphanumeric characters.
Syntax
str.isa1num()
Parameters
NA
Return Value
TRUE if all characters in the string are alphanumeric and there is at least one
character, FASLE otherwise.
Example
#!/usr/bin/python
Result
True
False
isalpha()
The method isalpha() checks whether the string consists of alphabetic characters
only.
Syntax
Following is the syntax for islpha() method:
str.isalpha()
90
Pyth
Parameters
NA
Return Value
This method returns true if all characters in the string are alphabetic and there is at
least one character, false otherwise.
Example
The following example shows the usage of isalpha() method.
#!/usr/bin/python
True
False
isdigit()
The method isdigit() checks whether the string consists of digits only.
Syntax
Following is the syntax for isdigit() method:
str.isdigit()
Parameters
NA
Return Value
This method returns true if all characters in the string are digits and there is at least
one character, false otherwise.
91
Pyth
Example
The following example shows the usage of isdigit() method.
#!/usr/bin/python
True
False
islower()
Description
The method islower() checks whether all the case-based characters (letters) of the
string are lowercase.
Syntax
Following is the syntax for islower() method:
str.islower()
Parameters
NA
Return Value
This method returns true if all cased characters in the string are lowercase and there
is at least one cased character, false otherwise.
92
Pyth
Example
The following example shows the usage of islower() method.
#!/usr/bin/python
False
True
isnumeric()
Description
The method isnumeric() checks whether the string consists of only numeric
characters. This method is present only on unicode objects.
Note: To define a string as Unicode, one simply prefixes a 'u' to the opening
quotation mark of the assignment. Below is the example.
Syntax
Following is the syntax for isnumeric() method:
str.isnumeric()
Parameters
NA
Return Value
This method returns true if all characters in the string are numeric, false otherwise.
93
Pyth
Example
The following example shows the usage of isnumeric() method.
#!/usr/bin/python
str = u"this2009";
print str.isnumeric();
str = u"23443434";
print str.isnumeric();
False
True
isspace() Method
The method isspace() checks whether the string consists of whitespace.
Syntax
Following is the syntax for isspace() method:
str.isspace()
Parameters
NA
Return Value
This method returns true if there are only whitespace characters in the string and
there is at least one character, false otherwise.
Example
The following example shows the usage of isspace() method.
#!/usr/bin/python
94
Pyth
True
False
istitle()
The method istitle() checks whether all the case-based characters in the string
following non-casebased letters are uppercase and all other case-based characters
are lowercase.
Syntax
Following is the syntax for istitle() method:
str.istitle()
Parameters
NA
Return Value
This method returns true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters
and lowercase characters only cased ones.It returns false otherwise.
Example
The following example shows the usage of istitle() method.
#!/usr/bin/python
True
False
95
Pyth
isupper()
The method isupper() checks whether all the case-based characters (letters) of the
string are uppercase.
Syntax
Following is the syntax for isupper() method:
str.isupper()
Parameters
NA
Return Value
This method returns true if all cased characters in the string are uppercase and
there is at least one cased character, false otherwise.
Example
The following example shows the usage of isupper() method.
#!/usr/bin/python
True
False
join(seq)
Description
The method join() returns a string in which the string elements of sequence have
been joined by str separator.
96
Pyth
Syntax
Following is the syntax for join() method:
str.join(sequence)
Parameters
sequence -- This is a sequence of the elements to be joined.
Return Value
This method returns a string, which is the concatenation of the strings in the
sequence seq. The separator between elements is the string providing this method.
Example
The following example shows the usage of join() method.
#!/usr/bin/python
str = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print str.join( seq );
a-b-c
len(string)
The method len() returns the length of the string.
Syntax
Following is the syntax for len() method:
len( str )
Parameters
NA
Return Value
This method returns the length of the string.
97
Pyth
Example
The following example shows the usage of len() method.
#!/usr/bin/python
ljust(width[, fillchar])
The method ljust() returns the string left justified in a string of length width.
Padding is done using the specified fillchar (default is a space). The original string is
returned if width is less than len(s).
Syntax
Following is the syntax for ljust() method:
str.ljust(width[, fillchar])
Parameters
width -- This is string length in total after padding.
fillchar -- This is filler character, default is a space.
Return Value
This method returns the string left justified in a string of length width. Padding is
done using the specified fillchar (default is a space). The original string is returned
if width is less than len(s).
Example
The following example shows the usage of ljust() method.
#!/usr/bin/python
98
Pyth
lower()
The method lower() returns a copy of the string in which all case-based characters
have been lowercased.
Syntax
Following is the syntax for lower() method:
str.lower()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been
lowercased.
Example
The following example shows the usage of lower() method.
#!/usr/bin/python
print str.lower();
99
Pyth
lstrip()
The method lstrip() returns a copy of the string in which all chars have been
stripped from the beginning of the string (default whitespace characters).
Syntax
Following is the syntax for lstrip() method:
str.lstrip([chars])
Parameters
chars -- You can supply what chars have to be trimmed.
Return Value
This method returns a copy of the string in which all chars have been stripped from
the beginning of the string (default whitespace characters).
Example
The following example shows the usage of lstrip() method.
#!/usr/bin/python
maketrans()
The method maketrans() returns a translation table that maps each character in
the intabstring into the character at the same position in the outtab string. Then
this table is passed to the translate() function.
Note: Both intab and outtab must have the same length.
10
Pyth
Syntax
Following is the syntax for maketrans() method:
str.maketrans(intab, outtab]);
Parameters
intab -- This is the string having actual characters.
outtab -- This is the string having corresponding mapping character.
Return Value
This method returns a translate table to be used translate() function.
Example
The following example shows the usage of maketrans() method. Under this, every
vowel in a string is replaced by its vowel position:
#!/usr/bin/python
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
10
Pyth
max(str)
The method max() returns the max alphabetical character from the string str.
Syntax
Following is the syntax for max() method:
max(str)
Parameters
str -- This is the string from which max alphabetical character needs to be
returned.
Return Value
This method returns the max alphabetical character from the string str.
Example
The following example shows the usage of max() method.
#!/usr/bin/python
Max character: y
Max character: x
min(str)
The method min() returns the min alphabetical character from the string str.
Syntax
Following is the syntax for min() method:
min(str)
10
Pyth
Parameters
str -- This is the string from which min alphabetical character needs to be
returned.
Return Value
This method returns the max alphabetical character from the string str.
Example
The following example shows the usage of min() method.
#!/usr/bin/python
Min character: !
Min character: !
Syntax
Following is the syntax for replace() method:
Parameters
old -- This is old substring to be replaced.
new -- This is new substring, which would replace old substring.
max -- If this optional argument max is given, only the first count
occurrences are replaced.
10
Pyth
Return Value
This method returns a copy of the string with all occurrences of substring old
replaced by new. If the optional argument max is given, only the first count
occurrences are replaced.
Example
The following example shows the usage of replace() method.
#!/usr/bin/python
rfind(str, beg=0,end=len(string)
Description
The method rfind() returns the last index where the substring str is found, or -1 if
no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rfind() method:
Parameters
str -- This specifies the string to be searched.
beg -- This is the starting index, by default its 0.
end -- This is the ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found and -1 otherwise.
10
Pyth
Example
The following example shows the usage of rfind() method.
#!/usr/bin/python
print str.rfind(str);
print str.rfind(str, 0, 10);
print str.rfind(str, 10, 0);
print str.find(str);
print str.find(str, 0, 10);
print str.find(str, 10, 0);
5
5
-1
2
2
-1
Syntax
Following is the syntax for rindex() method:
Parameters
10
Pyth
Return Value
This method returns last index if found otherwise raises an exception if str is not
found.
Example
The following example shows the usage of rindex() method.
#!/usr/bin/python
print str1.rindex(str2);
print str1.index(str2);
5
2
Syntax
Following is the syntax for rjust() method:
str.rjust(width[, fillchar])
Parameters
10
Pyth
Return Value
This method returns the string right justified in a string of length width. Padding is
done using the specified fillchar (default is a space). The original string is returned
if width is less than len(s).
Example
The following example shows the usage of rjust() method.
#!/usr/bin/python
rstrip()
The method rstrip() returns a copy of the string in which all chars have been
stripped from the end of the string (default whitespace characters).
Syntax
Following is the syntax for rstrip() method:
str.rstrip([chars])
Parameters
chars -- You can supply what chars have to be trimmed.
Return Value
This method returns a copy of the string in which all chars have been stripped from
the end of the string (default whitespace characters).
Example
10
Pyth
#!/usr/bin/python
split(str="", num=string.count(str)
The method split() returns a list of all the words in the string, using str as the
separator (splits on all whitespace if left unspecified), optionally limiting the number
of splits to num.
Syntax
Following is the syntax for split() method:
str.split(str="", num=string.count(str)).
Parameters
str -- This is any delimeter, by default it is space.
num -- this is number of lines to be made.
Return Value
This method returns a list of lines.
Example
The following example shows the usage of split() method.
10
Pyth
#!/usr/bin/python
splitlines(num=string.count('\n'))
The method splitlines() returns a list with all the lines in string, optionally including
the line breaks (if num is supplied and is true)
Syntax
Following is the syntax for splitlines() method:
str.splitlines( num=string.count('\n'))
Parameters
num -- This is any number, if present then it would be assumed that line
breaks need to be included in the lines.
Return Value
This method returns true if found matching string otherwise false.
Example
The following example shows the usage of splitlines() method.
#!/usr/bin/python
10
Pyth
startswith(str, beg=0,end=len(string)
The method startswith() checks whether string starts with str, optionally
restricting the matching with the given indices start and end.
Syntax
Following is the syntax for startswith() method:
str.startswith(str, beg=0,end=len(string));
Parameters
str -- This is the string to be checked.
beg -- This is the optional parameter to set start index of the matching
boundary.
end -- This is the optional parameter to set start index of the matching
boundary.
Return Value
This method returns true if found matching string otherwise false.
Example
The following example shows the usage of startswith() method.
#!/usr/bin/python
11
Pyth
True
True
False
strip([chars])
The method strip() returns a copy of the string in which all chars have been
stripped from the beginning and the end of the string (default whitespace
characters).
Syntax
Following is the syntax for strip() method:
str.strip([chars]);
Parameters
chars -- The characters to be removed from beginning or end of the string.
Return Value
This method returns a copy of the string in which all chars have been stripped from
the beginning and the end of the string.
Example
The following example shows the usage of strip() method.
#!/usr/bin/python
swapcase()
The method swapcase() returns a copy of the string in which all the case-based
characters have had their case swapped.
11
Pyth
Syntax
Following is the syntax for swapcase() method:
str.swapcase();
Parameters
NA
Return Value
This method returns a copy of the string in which all the case-based characters have
had their case swapped.
Example
The following example shows the usage of swapcase() method.
#!/usr/bin/python
title()
The method title() returns a copy of the string in which first characters of all the
words are capitalized.
Syntax
Following is the syntax for title() method:
str.title();
Parameters
NA
Return Value
11
Pyth
This method returns a copy of the string in which first characters of all the words
are capitalized.
Example
The following example shows the usage of title() method.
#!/usr/bin/python
translate(table, deletechars="")
The method translate() returns a copy of the string in which all characters have
been translated using table (constructed with the maketrans() function in the string
module), optionally deleting all characters found in the string deletechars.
Syntax
Following is the syntax for translate() method:
str.translate(table[, deletechars]);
Parameters
table -- You can use the maketrans() helper function in the string module to
create a translation table.
Return Value
This method returns a translated copy of the string.
Example
The following example shows the usage of translate() method. Under this every
vowel in a string is replaced by its vowel position:
11
Pyth
#!/usr/bin/python
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
Following is the example to delete 'x' and 'm' characters from the string:
#!/usr/bin/python
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
upper()
The method upper() returns a copy of the string in which all case-based characters
have been uppercased.
Syntax
Following is the syntax for upper() method:
11
Pyth
str.upper()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been
uppercased.
Example
The following example shows the usage of upper() method.
#!/usr/bin/python
zfil (width)
The method zfill() pads string on the left with zeros to fill width.
Syntax
Following is the syntax for zfill() method:
str.zfill(width)
Parameters
width -- This is final width of the string. This is the width which we would
get after filling zeros.
Return Value
This method returns padded string.
11
Pyth
Example
The following example shows the usage of zfill() method.
#!/usr/bin/python
print str.zfill(40);
print str.zfill(50);
isdecimal()
The method isdecimal() checks whether the string consists of only decimal
characters. This method are present only on unicode objects.
Note: To define a string as Unicode, one simply prefixes a 'u' to the opening
quotation mark of the assignment. Below is the example.
Syntax
Following is the syntax for isdecimal() method:
str.isdecimal()
Parameters
NA
Return Value
This method returns true if all characters in the string are decimal, false otherwise.
Example
The following example shows the usage of isdecimal() method.
#!/usr/bin/python
str = u"this2009";
11
Pyth
print str.isdecimal();
str = u"23443434";
print str.isdecimal();
False
True
11
10. Python ─ Lists Pyth
The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the
second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and
tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.
#!/usr/bin/python
11
Pyth
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with
the append() method. For example:
#!/usr/bin/python
#!/usr/bin/python
11
Pyth
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
In fact, lists respond to all of the general sequence operations we used on strings in
the prior chapter.
12
Pyth
Sr.
Function with Description
No.
cmp(list1, list2)
1
Compares elements of both lists.
len(list)
2
Gives the total length of the list.
max(list)
3
Returns item from the list with max value.
min(list)
4
Returns item from the list with min value.
list(seq)
5
Converts a tuple into list.
12
Pyth
Cmp(list1, list2)
The method cmp() compares elements of two lists.
Syntax
Following is the syntax for cmp() method:
cmp(list1, list2)
Parameters
list1 -- This is the first list to be compared.
list2 -- This is the second list to be compared.
Return Value
If elements are of the same type, perform the compare and return the result. If
elements are different types, check to see if they are numbers.
If we reached the end of one of the lists, the longer list is "larger." If we exhaust
both lists and share the same data, the result is a tie, meaning that 0 is returned.
Example
The following example shows the usage of cmp() method.
#!/usr/bin/python
12
Pyth
-1
1
-1
len(List)
The method len() returns the number of elements in the list.
Syntax
Following is the syntax for len() method:
len(list)
Parameters
list -- This is a list for which number of elements to be counted.
Return Value
This method returns the number of elements in the list.
Example
The following example shows the usage of len() method.
#!/usr/bin/python
12
Pyth
max(list)
The method max returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method:
max(list)
Parameters
list -- This is a list from which max valued element to be returned.
Return Value
This method returns the elements from the list with maximum value.
Example
The following example shows the usage of max() method.
#!/usr/bin/python
min(list)
The method min() returns the elements from the list with minimum value.
Syntax
Following is the syntax for min() method:
min(list)
12
Pyth
Parameters
list -- This is a list from which min valued element to be returned.
Return Value
This method returns the elements from the list with minimum value.
Example
The following example shows the usage of min() method.
#!/usr/bin/python
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
12
Pyth
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
List.append(obj)
The method append() appends a passed obj into the existing list.
Syntax
Following is the syntax for append() method:
list.append(obj)
Parameters
obj -- This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list.
Example
The following example shows the usage of append() method.
#!/usr/bin/python
12
Pyth
list.count(obj)
The method count() returns count of how many times obj occurs in list.
Syntax
Following is the syntax for count() method:
list.count(obj)
Parameters
obj -- This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
Example
The following example shows the usage of count() method.
#!/usr/bin/python
12
Pyth
list.extend(seq)
The method extend() appends the contents of seq to list.
Syntax
Following is the syntax for extend() method:
list.extend(seq)
Parameters
seq -- This is the list of elements
Return Value
This method does not return any value but add the content to existing list.
Example
The following example shows the usage of extend() method.
#!/usr/bin/python
list.index(obj)
The method index() returns the lowest index in list that obj appears.
Syntax
Following is the syntax for index() method:
list.index(obj)
12
Pyth
Parameters
obj -- This is the object to be find out.
Return Value
This method returns index of the found object otherwise raise an exception
indicating that value does not find.
Example
The following example shows the usage of index() method.
#!/usr/bin/python
list.insert(index,obj)
The method insert() inserts object obj into list at offset index.
Syntax
Following is the syntax for insert() method:
list.insert(index, obj)
Parameters
index -- This is the Index where the object obj need to be inserted.
obj -- This is the Object to be inserted into the given list.
Return Value
This method does not return any value but it inserts the given element at the given
index.
12
Pyth
Example
The following example shows the usage of insert() method.
#!/usr/bin/python
aList.insert( 3, 2009)
list.pop(obj=list[-1])
The method pop() removes and returns last object or obj from the list.
Syntax
Following is the syntax for pop() method:
list.pop(obj=list[-1])
Parameters
obj -- This is an optional parameter, index of the object to be removed from
the list.
Return Value
This method returns the removed object from the list.
Example
The following example shows the usage of pop() method.
#!/usr/bin/python
13
Pyth
A List : abc
B List : zara
List.remove(obj)
Parameters
obj -- This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the list.
Example
The following example shows the usage of remove() method.
#!/usr/bin/python
aList.remove('xyz');
print "List : ", aList;
aList.remove('abc');
print "List : ", aList;
List.reverse()
The method reverse() reverses objects of list in place.
Syntax
Following is the syntax for reverse() method:
list.reverse()
13
Pyth
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list.
Example
The following example shows the usage of reverse() method.
#!/usr/bin/python
aList.reverse();
print "List : ", aList;
list.sort([func])
The method reverse() reverses objects of list in place.
Syntax
Following is the syntax for reverse() method:
list.reverse()
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list.
13
Pyth
Example
The following example shows the usage of reverse() method.
#!/usr/bin/python
aList.reverse();
print "List : ", aList;
13
11. Python ─ Tuples Pyth
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.
tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value:
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated,
and so on.
#!/usr/bin/python
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
13
Pyth
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
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
print tup;
del tup;
print "After deleting tup : "
print tup;
13
Pyth
This produces the following result. Note an exception raised, this is because after
del tup, tuple does not exist anymore:
In fact, tuples respond to all of the general sequence operations we used on strings
in the prior chapter:
13
Pyth
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
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
13
Pyth
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Cmp(tuple1, tuple2)
The method cmp() compares elements of two tuples.
Syntax
Following is the syntax for cmp() method:
cmp(tuple1, tuple2)
Parameters
tuple1 -- This is the first tuple to be compared
tuple2 -- This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result. If
elements are different types, check to see if they are numbers.
If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust
both tuples and share the same data, the result is a tie, meaning that 0 is returned.
13
Pyth
Example
The following example shows the usage of cmp() method.
#!/usr/bin/python
-1
1
-1
Len(tuple)
The method len() returns the number of elements in the tuple.
Syntax
Following is the syntax for len() method:
len(tuple)
Parameters
tuple -- This is a tuple for which number of elements to be counted.
Return Value
This method returns the number of elements in the tuple.
Example
The following example shows the usage of len() method.
#!/usr/bin/python
13
Pyth
Max(tuple)
The method max() returns the elements from the tuple with maximum value.
Syntax
Following is the syntax for max() method:
max(tuple)
Parameters
tuple -- This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value.
Example
The following example shows the usage of max() method.
#!/usr/bin/python
14
Pyth
Min(tuple)
The method min() returns the elements from the tuple with minimum value.
Syntax
Following is the syntax for min() method:
min(tuple)
Parameters
tuple -- This is a tuple from which min valued element to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example
The following example shows the usage of min() method.
#!/usr/bin/python
Tuple(seg)
The method tuple() compares elements of two tuples.
Syntax
Following is the syntax for tuple() method:
tuple( seq )
14
Pyth
Parameters
seq -- This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
Example
The following example shows the usage of tuple() method.
#!/usr/bin/python
14
12. Python ─ Dictionary Pyth
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
#!/usr/bin/python
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error as follows:
#!/usr/bin/python
14
Pyth
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple example:
#!/usr/bin/python
dict['Age']: 8
dict['School']: DPS School
To explicitly remove an entire dictionary, just use the del statement. For example:
#!/usr/bin/python
14
Pyth
This produces the following result. Note that an exception is raised because after del
dict, dictionary does not exist anymore:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last assignment
wins. For example:
#!/usr/bin/python
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples
as dictionary keys but something like ['key'] is not allowed. Following is a simple
example:
14
Pyth
#!/usr/bin/python
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3 str(dict)
4 type(variable)
Cmp(dict1, dict2)
The method cmp() compares two dictionaries based on key and values.
14
Pyth
Syntax
Following is the syntax for cmp() method:
cmp(dict1, dict2)
Parameters
dict1 -- This is the first dictionary to be compared with dict2.
dict2 -- This is the second dictionary to be compared with dict1.
Return Value
This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2, and 1 if dict1
> dic2.
Example
The following example shows the usage of cmp() method.
#!/usr/bin/python
Return Value : -1
Return Value : 1
Return Value : 0
len(dict)
The method len() gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
Syntax
14
Pyth
len(dict)
Parameters
dict -- This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example
The following example shows the usage of len() method.
#!/usr/bin/python
Length : 2
str(dict)
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method:
str(dict)
Parameters
dict -- This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
14
Pyth
#!/usr/bin/python
type()
The method type() returns the type of the passed variable. If passed variable is
dictionary then it would return a dictionary type.
Syntax
Following is the syntax for type() method:
type(dict)
Parameters
dict -- This is the dictionary.
Return Value
This method returns the type of the passed variable.
Example
The following example shows the usage of type() method.
#!/usr/bin/python
14
Pyth
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
5 dict.has_key(key)
6 dict.items()
7 dict.keys()
8 dict.setdefault(key, default=None)
10 dict.values()
15
Pyth
dict.clear()
The method clear() removes all items from the dictionary.
Syntax
Following is the syntax for clear() method:
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of clear() method.
#!/usr/bin/python
Start Len : 2
End Len : 0
Dict.copy()
The method copy() returns a shallow copy of the dictionary.
Syntax
Following is the syntax for copy() method:
15
Pyth
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
Example
The following example shows the usage of copy() method.
#!/usr/bin/python
dict2 = dict1.copy()
print "New Dictinary : %s" % str(dict2)
Dict.fromkeys()
The method fromkeys() creates a new dictionary with keys from seq and values set
to value.
Syntax
Following is the syntax for fromkeys() method:
dict.fromkeys(seq[, value]))
Parameters
seq -- This is the list of values which would be used for dictionary keys
preparation.
value -- This is optional, if provided then value would be set to this value
15
Pyth
Return Value
This method returns the list.
Example
The following example shows the usage of fromkeys() method.
#!/usr/bin/python
dict = dict.fromkeys(seq)
print "New Dictionary : %s" % str(dict)
Dict.get(key,default=none)
The method get() returns a value for the given key. If key is not available then
returns default value None.
Syntax
Following is the syntax for get() method:
dict.get(key, default=None)
Parameters
key -- This is the Key to be searched in the dictionary.
default -- This is the Value to be returned in case key does not exist.
Return Value
15
Pyth
This method return a value for the given key. If key is not available, then returns
default value None.
Example
The following example shows the usage of get() method.
#!/usr/bin/python
Value : 7
Value : Never
Dict.has_key(key)
The method has_key() returns true if a given key is available in the dictionary,
otherwise it returns a false.
Syntax
Following is the syntax for has_key() method:
dict.has_key(key)
Parameters
key -- This is the Key to be searched in the dictionary.
Return Value
This method return true if a given key is available in the dictionary, otherwise it
returns a false.
Example
The following example shows the usage of has_key() method.
#!/usr/bin/python
15
Pyth
Value : True
Value : False
Dict.items()
The method items() returns a list of dict's (key, value) tuple pairs
Syntax
Following is the syntax for items() method:
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
Example
The following example shows the usage of items() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
15
Pyth
Dict.keys()
The method keys() returns a list of all the available keys in the dictionary.
Syntax
Following is the syntax for keys() method:
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example
The following example shows the usage of keys() method.
#!/usr/bin/python
dict.setdefault(key, default=None)
The method setdefault() is similar to get(), but will set dict[key]=default if key is
not already in dict.
Syntax
Following is the syntax for setdefault() method:
15
Pyth
dict.setdefault(key, default=None)
Parameters
key -- This is the key to be searched.
default -- This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if given key is not
available then it will return provided default value.
Example
The following example shows the usage of setdefault() method.
#!/usr/bin/python
Value : 7
Value : None
dict.update(dict2)
The method update() adds dictionary dict2's key-values pairs in to dict. This
function does not return anything.
Syntax
Following is the syntax for update() method:
dict.update(dict2)
15
Pyth
Parameters
dict2 -- This is the dictionary to be added into dict.
Return Value
This method does not return any value.
Example
The following example shows the usage of update() method.
#!/usr/bin/python
dict.update(dict2)
print "Value : %s" % dict
dict.values()
The method values() returns a list of all the values available in a given dictionary.
Syntax
Following is the syntax for values() method:
dict.values()
Parameters
NA
15
Pyth
Return Value
This method returns a list of all the values available in a given dictionary.
Example
The following example shows the usage of values() method.
#!/usr/bin/python
15
13. Python ─ Date and Time Pyth
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, 1970(epoch).
There is a popular time module available in Python which provides functions for
working with times and for converting between representations. The
function time.time() returns the current system time in ticks since 12:00am,
January 1, 1970(epoch).
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:
16
Pyth
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
The above tuple is equivalent to struct_time structure. This structure has following
attributes:
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
16
Pyth
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
This would produce the following result, which could be formatted in any other
presentable form:
#!/usr/bin/python
import time;
16
Pyth
#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;
time.altzone
1 The offset of the local DST timezone, in seconds west of UTC, if one
is defined. This is negative if the local DST timezone is east of UTC
(as in Western Europe, including the UK). Only use this if daylight is
nonzero.
2 time.asctime([tupletime])
16
Pyth
time.clock( )
time.ctime([secs])
4
Like asctime(localtime(secs)) and without arguments is like asctime( )
time.gmtime([secs])
5 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])
time.mktime(tupletime)
time.sleep(secs)
8
Suspends the calling thread for secs seconds.
time.strftime(fmt[,tupletime])
9 Accepts an instant expressed as a time-tuple in local time and returns
a string representing the instant as specified by string fmt.
16
Pyth
time.time( )
11 Returns the current time instant, a floating-point number of seconds
since the epoch.
time.tzset()
12 Resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.
time.altzone
The method altzone() is the attribute of the time module. This returns the offset
of the local DST timezone, in seconds west of UTC, if one is defined. This is
negative if the local DST timezone is east of UTC (as in Western Europe, including
the UK). Only use this if daylight is nonzero.
Syntax
Following is the syntax for altzone() method:
time.altzone
Parameters
NA
Return Value
This method returns the offset of the local DST timezone, in seconds west of UTC, if
one is defined.
Example
The following example shows the usage of altzone() method.
#!/usr/bin/python
import time
time.altzone() 25200
16
Pyth
time.actime([tupletime])
The method asctime() converts a tuple or struct_time representing a time as
returned by gmtime() or localtime() to a 24-character string of the following form:
'Tue Feb 17 23:21:05 2009'.
Syntax
Following is the syntax for asctime() method:
time.asctime([t]))
Parameters
t -- This is a tuple of 9 elements or struct_time representing a time as
returned by gmtime() or localtime() function.
Return Value
This method returns 24-character string of the following form: 'Tue Feb 17
23:21:05 2009'.
Example
The following example shows the usage of asctime() method.
#!/usr/bin/python
import time
t = time.localtime()
print "time.asctime(t): %s " % time.asctime(t)
time.clock( )
The method clock() returns the current processor time as a floating point number
expressed in seconds on Unix. The precision depends on that of the C function of
the same name, but in any case, this is the function to use for benchmarking
Python or timing algorithms.
On Windows, this function returns wall-clock seconds elapsed since the first call to
this function, as a floating point number, based on the Win32 function
QueryPerformanceCounter.
16
Pyth
Syntax
Following is the syntax for clock() method:
time.clock()
Parameters
NA
Return Value
This method returns the current processor time as a floating point number
expressed in seconds on Unix and in Windows it returns wall-clock seconds elapsed
since the first call to this function, as a floating point number.
Example
The following example shows the usage of clock() method.
#!/usr/bin/python
import time
def procedure():
time.sleep(2.5)
Note: Not all systems can measure the true process time. On such systems
(including Windows), clock usually measures the wall time since the program was
started.
16
Pyth
time.ctime([secs])
The method ctime() converts a time expressed in seconds since the epoch to a
string representing local time. If secs is not provided or None, the current time as
returned by time() is used. This function is equivalent to asctime(localtime(secs)).
Locale information is not used by ctime().
Syntax
Following is the syntax for ctime() method:
time.ctime([ sec ])
Parameters
sec -- These are the number of seconds to be converted into string
representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of ctime() method.
#!/usr/bin/python
import time
time.gmtime([secs])
The method gmtime() converts a time expressed in seconds since the epoch to a
struct_time in UTC in which the dst flag is always zero. If secs is not provided or
None, the current time as returned by time() is used.
Syntax
Following is the syntax for gmtime() method:
16
Pyth
time.gmtime([ sec ])
Parameters
sec -- These are the number of seconds to be converted into structure
struct_time representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of gmtime() method.
#!/usr/bin/python
import time
time.localtime([secs])
The method localtime() is similar to gmtime() but it converts number of seconds
to local time. If secs is not provided or None, the current time as returned by time()
is used. The dst flag is set to 1 when DST applies to the given time.
Syntax
Following is the syntax for localtime() method:
time.localtime([ sec ])
Parameters
sec -- These are the number of seconds to be converted into structure
struct_time representation.
Return Value
This method does not return any value.
16
Pyth
Example
The following example shows the usage of localtime() method.
#!/usr/bin/python
import time
time.mktime(tupletime)
Description
The method mktime() is the inverse function of localtime(). Its argument is the
struct_time or full 9-tuple and it returns a floating point number, for compatibility
with time().
Syntax
Following is the syntax for mktime() method:
time.mktime(t)
Parameters
t -- This is the struct_time or full 9-tuple.
Return Value
This method returns a floating point number, for compatibility with time().
Example
The following example shows the usage of mktime() method.
#!/usr/bin/python
import time
17
Pyth
secs = time.mktime( t )
print "time.mktime(t) : %f" % secs
print "asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs))
time.mktime(t) : 1234915418.000000
asctime(localtime(secs)): Tue Feb 17 17:03:38 2009
time.sleep(secs)
The method sleep() suspends execution for the given number of seconds. The
argument may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught
signal will terminate the sleep() following execution of that signal's catching routine.
Syntax
Following is the syntax for sleep() method:
time.sleep(t)
Parameters
t -- This is the number of seconds execution to be suspended.
Return Value
This method does not return any value.
Example
The following example shows the usage of sleep() method.
#!/usr/bin/python
import time
17
Pyth
time.strftime(fmt[,tupletime])
The method strftime() converts a tuple or struct_time representing a time as
returned by gmtime() or localtime() to a string as specified by the format
argument.
Syntax
Following is the syntax for strftime() method:
time.strftime(format[, t])
Parameters
t -- This is the time in number of seconds to be formatted.
format -- This is the directive which would be used to format given time.
The following directives can be embedded in the format string:
Directive
%a - abbreviated weekday name
%A - full weekday name
%b - abbreviated month name
%B - full month name
%c - preferred date and time representation
%C - century number (the year divided by 100, range 00 to 99)
%d - day of the month (01 to 31)
%D - same as %m/%d/%y
%e - day of the month (1 to 31)
%g - like %G, but without the century
%G - 4-digit year corresponding to the ISO week number (see %V).
%h - same as %b
%H - hour, using a 24-hour clock (00 to 23)
17
Pyth
%U - week number of the current year, starting with the first Sunday as the
first day of the first week
%V - The ISO 8601 week number of the current year (01 to 53), where week
1 is the first week that has at least 4 days in the current year, and with
Monday as the first day of the week
%W - week number of the current year, starting with the first Monday as the
first day of the first week
Return Value
This method does not return any value.
Example
17
Pyth
#!/usr/bin/python
import time
The format parameter uses the same directives as those used by strftime(); it
defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned
by ctime().
If string cannot be parsed according to format, or if it has excess data after parsing,
ValueError is raised.
Syntax
Following is the syntax for strptime() method:
time.strptime(string[, format])
Parameters
string -- This is the time in string format which would be parsed based on
the given format.
format -- This is the directive which would be used to parse the given string.
Directive
17
Pyth
%U - week number of the current year, starting with the first Sunday as the
first day of the first week
%V - The ISO 8601 week number of the current year (01 to 53), where week
1 is the first week that has at least 4 days in the current year, and with
Monday as the first day of the week
17
Pyth
%W - week number of the current year, starting with the first Monday as the
first day of the first week
Return Value
This return value is struct_time as returned by gmtime() or localtime().
Example
The following example shows the usage of strptime() method.
#!/usr/bin/python
import time
time.time( )
The method time() returns the time as a floating point number expressed in
seconds since the epoch, in UTC.
Note: Even though the time is always returned as a floating point number, not all
systems provide time with a better precision than 1 second. While this function
normally returns non-decreasing values, it can return a lower value than a previous
call if the system clock has been set back between the two calls.
Syntax
Following is the syntax for time() method:
17
Pyth
time.time()
Parameters
NA
Return Value
This method returns the time as a floating point number expressed in seconds since
the epoch, in UTC.
Example
The following example shows the usage of time() method.
#!/usr/bin/python
import time
time.time(): 1234892919.655932
(2009, 2, 17, 10, 48, 39, 1, 48, 0)
Tue Feb 17 10:48:39 2009
time.tzset()
The method tzset() resets the time conversion rules used by the library routines.
The environment variable TZ specifies how this is done.
The standard format of the TZ environment variable is (whitespace added for clarity):
offset: The offset has the form: .hh[:mm[:ss]]. This indicates the value added
the local time to arrive at UTC. If preceded by a '-', the timezone is east of
the Prime Meridian; otherwise, it is west. If no offset follows dst, summer
time is assumed to be one hour ahead of standard time.
17
Pyth
o Jn: The Julian day n (1 <= n <= 365). Leap days are not counted, so
in all years February 28 is day 59 and March 1 is day 60.
o n: The zero-based Julian day (0 <= n <= 365). Leap days are
counted, and it is possible to refer to February 29.
o time: This has the same format as offset except that no leading sign
('- ' or '+') is allowed. The default, if time is not given, is 02:00:00.
Syntax
Following is the syntax for tzset() method:
time.tzset()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of tzset() method.
17
Pyth
#!/usr/bin/python
import time
import os
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print time.strftime('%X %x %Z')
os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
time.tzset()
17
Pyth
There are following two important attributes available with time module:
Sr.
Attribute with Description
No.
time.timezone
time.tzname
2 Attribute time.tzname is a pair of locale-dependent strings, which are the
names of the local time zone without and with DST, respectively.
By default, calendar takes Monday as the first day of the week and Sunday as the
last one. To change this, call calendar.setfirstweekday() function.
1 calendar.calendar(year,w=2,l=1,c=6)
18
Pyth
Returns a multiline string with a calendar for 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.
calendar.firstweekday( )
2 Returns the current setting for the weekday that starts each week. By
default, when calendar is first imported, this is 0, meaning Monday.
calendar.isleap(year)
3
Returns True if year is a leap year; otherwise, False.
calendar.leapdays(y1,y2)
4
Returns the total number of leap days in the years within range(y1,y2).
calendar.month(year,month,w=2,l=1)
5 Returns a multiline string with a calendar for month of 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.monthcalendar(year,month)
6 Returns a list of lists of ints. Each sublist denotes a week. Days outside
month of year are set to 0; days within the month are set to their day-
of-month, 1 and up.
calendar.monthrange(year,month)
Returns two integers. The first one is the code of the weekday for the
7 first day of the month month in 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.
18
Pyth
calendar.setfirstweekday(weekday)
10 Sets the first day of each week to weekday code weekday. Weekday
codes are 0 (Monday) to 6 (Sunday).
calendar.timegm(tupletime)
calendar.weekday(year,month,day)
12 Returns the weekday code for the given date. Weekday codes are 0
(Monday) to 6 (Sunday); month numbers are 1 (January) to 12
(December).
18
14. Python ─ Functions Pyth
As you already know, Python gives you many built-in functions such as print() and
but you can also create your own functions. These functions are called user-defined
functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules
to define a function in Python.
Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
The code block within every function starts with a colon (:) and is indented.
Syntax
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.
18
Pyth
Example
The following function takes a string as input parameter and prints it on standard
screen.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
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
18
Pyth
#!/usr/bin/python
Here, we are maintaining reference of the passed object and appending values in
the same object. So, this would produce the following result:
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
18
Pyth
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:
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();
18
Pyth
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
My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
#!/usr/bin/python
18
Pyth
Name: miki
Age 50
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
Name: miki
Age 50
Name: miki
Age 35
18
Pyth
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
Output is:
10
Output is:
70
60
50
18
Pyth
Lambda forms can take any number of arguments but return just one value
in the form of an expression. They cannot contain commands or multiple
expressions.
Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows:
#!/usr/bin/python
Value of total : 30
Value of total : 40
18
Pyth
All the above examples are not returning any value. You can return a value from a
function as follows:
#!/usr/bin/python
Scope of Variables
All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
19
Pyth
This means that local variables can be accessed only inside the function in which
they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope. Following is a simple example:
#!/usr/bin/python
19
15. Python ─ Modules Pyth
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 is an example of a simple module, support.py
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
Hello : Zara
19
Pyth
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:
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:
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/.
19
Pyth
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.
set PYTHONPATH=c:\python20\lib;
set PYTHONPATH=/usr/local/lib/python
A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.
The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the
functionMoney, we assign Money a value, therefore Python assumes Money as a
local variable. However, we accessed the value of the local variable Money before
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.
19
Pyth
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The list contains the names of all the modules, variables and functions that are
defined in a module. Following is a simple example:
#!/usr/bin/python
content = dir(math)
print content;
[' doc ', '__file__', ' name ', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable name is the module's name, and file is the
filename from which the module was loaded.
19
Pyth
If locals() is called from within a function, it will return all the names that can
be accessed locally from that function.
If globals() is called from within a function, it will return all the names that
can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload()function. The reload() function imports a previously imported module
again. The syntax of the reload() function is this:
reload(module_name)
Here, module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do the
following:
reload(hello)
Packages in Python
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"
19
Pyth
Similar way, we have another two files having different functions with the same
name as above:
To make all of your functions available when you've imported Phone, you need to
put explicit import statements in init .py as follows:
After you add these lines to init .py, you have all of these classes available when
you import the Phone package.
#!/usr/bin/python
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.
19
16. Python ─ Files I/O Pyth
This chapter covers all the basic I/O functions available in Python. For more
functions, please refer to standard Python documentation.
#!/usr/bin/python
raw_input
input
#!/usr/bin/python
This prompts you to enter any string and it would display same string on the
screen. When I typed "Hello Python!", its output is like this:
19
Pyth
#!/usr/bin/python
This would produce the following result against the entered input:
Syntax
file object = open(file_name [, access_mode][, buffering])
file_name: The file_name argument is a string value that contains the name
of the file that you want to access.
access_mode: The access_mode determines the mode in which the file has
to be opened, i.e., read, write, append, etc. A complete list of possible values
19
Pyth
is given below in the table. This is optional parameter and the default file
access mode is read (r).
Modes Description
r 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 is placed at the
beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file
pointer is placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
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.
20
Pyth
a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
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.softspace Returns false if space explicitly required with print, true otherwise.
20
Pyth
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
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
20
Pyth
The write() method does not add a newline character ('\n') to the end of the string:
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
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.
20
Pyth
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
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
# Close opend file
fo.close()
File Positions
The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.
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.
20
Pyth
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
To use this module you need to import it first and then you can call any related
functions.
20
Pyth
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt:
#!/usr/bin/python
import os
20
Pyth
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
Syntax
os.chdir("newdir")
20
Pyth
Example
Following is the example to go into "/home/newdir" directory:
#!/usr/bin/python
import os
Syntax
os.getcwd()
Example
Following is the example to give current directory:
#!/usr/bin/python
import os
Syntax
os.rmdir('dirname')
20
Pyth
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
File Object Methods: The file object provides functions to manipulate files.
A file object is created using open function and here is a list of functions which can
be called on this object:
Sr. No. Methods with Description
file.close()
1
Close the file. A closed file cannot be read or written any more.
file.flush()
2 Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-
like objects.
file.fileno()
3 Returns the integer file descriptor that is used by the underlying implementation
to request I/O operations from the operating system.
file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.
file.next()
5
Returnss the next line from the file each time it is being called.
file.read([size])
6 Reads at most size bytes from the file (less if the read hits EOF before obtaining
size bytes).
20
Pyth
file.readline([size])
7 Reads one entire line from the file. A trailing newline character is kept in the
string.
file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If the
8 optional sizehint argument is present, instead of reading up to EOF, whole lines
totalling approximately sizehint bytes (possibly after rounding up to an internal
buffer size) are read.
file.seek(offset[,whence])
9
Sets the file's current position.
file.tell()
10
Returns the file's current position
file.truncate([size])
11 Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
file.write(str)
12
Writes a string to the file. There is no return value.
file.writelines(sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.
file.close()
The method close() closes the opened file. A closed file cannot be read or written
any more. Any operation, which requires that the file be opened will raise
a ValueError after the file has been closed. Calling close() more than once is
allowed.
Python automatically closes a file when the reference object of a file is reassigned
to another file. It is a good practice to use the close() method to close a file.
Syntax
Following is the syntax for close() method:
fileObject.close();
Parameters
NA
Return Value
This method does not return any value.
21
Pyth
Example
The following example shows the usage of close() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
File.flush()
The method flush() flushes the internal buffer, like stdio's fflush. This may be a no-
op on some file-like objects.
Python automatically flushes the files when closing them. But you may want to flush
the data before closing any file.
Syntax
Following is the syntax for flush() method:
fileObject.flush();
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of flush() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
21
Pyth
File.fileno()
The method fileno() returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.
Syntax
Following is the syntax for fileno() method:
fileObject.fileno();
Parameters
NA
Return Value
This method returns the integer file descriptor.
Example
The following example shows the usage of fileno() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fid = fo.fileno()
print "File Descriptor: ", fid
21
Pyth
File.isatty()
The method isatty() returns True if the file is connected (is associated with a
terminal device) to a tty(-like) device, else False.
Syntax
Following is the syntax for isatty() method:
fileObject.isatty();
Parameters
NA
Return Value
This method returns true if the file is connected (is associated with a terminal
device) to a tty(-like) device, else false.
Example
The following example shows the usage of isatty() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
ret = fo.isatty()
print "Return value : ", ret
21
Pyth
fo.close()
File.next()
The method next() is used when a file is used as an iterator, typically in a loop, the
next() method is called repeatedly. This method returns the next input line, or
raises StopIteration when EOF is hit.
Combining next() method with other file methods like readline() does not work
right. However, usingseek() to reposition the file to an absolute position will flush
the read- ahead buffer.
Syntax
Following is the syntax for next() method:
fileObject.next();
Parameters
NA
Return Value
This method returns the next input line.
Example
The following example shows the usage of next() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
21
Pyth
File.read([size])
The method read() reads at most size bytes from the file. If the read hits EOF
before obtaining size bytes, then it reads only available bytes.
Syntax
Following is the syntax for read() method:
fileObject.read( size );
Parameters
size -- This is the number of bytes to be read from the file.
Return Value
This method returns the bytes read in string.
21
Pyth
Example
The following example shows the usage of read() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.read(10)
print "Read Line: %s" % (line)
File.readline([size])
The method readline() reads one entire line from the file. A trailing newline
character is kept in the string. If the size argument is present and non-negative, it
is a maximum byte count including the trailing newline and an incomplete line may
be returned.
21
Pyth
Syntax
Following is the syntax for readline() method:
fileObject.readline( size );
Parameters
size -- This is the number of bytes to be read from the file.
Return Value
This method returns the line read from the file.
Example
The following example shows the usage of readline() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
line = fo.readline(5)
print "Read Line: %s" % (line)
21
Pyth
file.readline([sizehint])
The method readline() reads one entire line from the file. A trailing newline
character is kept in the string. If the size argument is present and non-negative, it
is a maximum byte count including the trailing newline and an incomplete line may
be returned.
Syntax
Following is the syntax for readline() method:
fileObject.readline( size );
Parameters
size -- This is the number of bytes to be read from the file.
Return Value
This method returns the line read from the file.
Example
The following example shows the usage of readline() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
21
Pyth
line = fo.readline()
print "Read Line: %s" % (line)
line = fo.readline(5)
print "Read Line: %s" % (line)
file.seek(offset[,whence])
The method seek() sets the file's current position at the offset. The whence
argument is optional and defaults to 0, which means absolute file positioning, other
values are 1 which means seek relative to the current position and 2 means seek
relative to the file's end.
There is no return value. Note that if the file is opened for appending using either
'a' or 'a+', any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is
essentially a no-op, but it remains useful for files opened in append mode with
reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal.
Use of other offsets causes undefined behavior.
Syntax
21
Pyth
fileObject.seek(offset[, whence])
Parameters
offset -- This is the position of the read/write pointer within the file.
Return Value
This method does not return any value.
Example
The following example shows the usage of seek() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
22
Pyth
file.tel ()
The method tell() returns the current position of the file read/write pointer within
the file.
Syntax
Following is the syntax for tell() method:
fileObject.tell()
Parameters
NA
Return Value
This method returns the current position of the file read/write pointer within the file.
Example
The following example shows the usage of tell() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
22
Pyth
line = fo.readline()
print "Read Line: %s" % (line)
file.truncate([size])
The method truncate() truncates the file's size. If the optional size argument is
present, the file is truncated to (at most) that size..
The size defaults to the current position. The current file position is not changed.
Note that if a specifiedsize exceeds the file's current size, the result is platform-
dependent.
Note: This method would not work in case file is opened in read-only mode.
Syntax
Following is the syntax for truncate() method:
fileObject.truncate( [ size ])
Parameters
size -- If this optional argument is present, the file is truncated to (at most) that
size.
22
Pyth
Return Value
This method does not return any value.
Example
The following example shows the usage of truncate() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
22
Pyth
Read Line:
file.write(str)
The method write() writes a string str to the file. There is no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.
Syntax
Following is the syntax for write() method:
fileObject.write( str )
Parameters
str -- This is the String to be written in the file.
Return Value
This method does not return any value.
Example
The following example shows the usage of write() method.
#!/usr/bin/python
22
Pyth
fo.seek(0, 2)
line = fo.write( str )
file.writelines(sequence)
The method writelines() writes a sequence of strings to the file. The sequence can
be any iterable object producing strings, typically a list of strings. There is no return
value.
Syntax
Following is the syntax for writelines() method:
fileObject.writelines( sequence )
Parameters
sequence -- This is the Sequence of the strings.
22
Pyth
Return Value
This method does not return any value.
Example
The following example shows the usage of writelines() method.
#!/usr/bin/python'
22
Pyth
OS Object Methods
This provides methods to process files as well as directories.
os.access(path,mode)
1
Use the real uid/gid to test for access to path.
os.chdir(path)
2
Change the current working directory to path
os.chflags(path, flags)
3
Set the flags of path to the numeric flags.
os.chmod(path, mode)
4
Change the mode of path to the numeric mode.
os.chroot(path)
6
Change the root directory of the current process to path.
os.close(fd)
7
Close file descriptor fd.
os.closerange(fd_low, fd_high)
8 Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring
errors.
os.dup(fd)
9
Return a duplicate of file descriptor fd.
22
Pyth
os.dup2(fd, fd2)
10
Duplicate file descriptor fd to fd2, closing the latter first if necessary.
os.fchdir(fd)
11 Change the current working directory to the directory represented by the file
descriptor fd.
os.fchmod(fd, mode)
12
Change the mode of the file given by fd to the numeric mode.
os.fdatasync(fd)
14
Force write of file with filedescriptor fd to disk.
os.fpathconf(fd, name)
16 Return system configuration information relevant to an open file. name specifies
the configuration value to retrieve.
os.fstat(fd)
17
Return status for file descriptor fd, like stat().
os.fstatvfs(fd)
18 Return information about the filesystem containing the file associated with file
descriptor fd, like statvfs().
os.fsync(fd)
19
Force write of file with filedescriptor fd to disk.
os.ftruncate(fd, length)
20 Truncate the file corresponding to file descriptor fd, so that it is at most length
bytes in size.
os.getcwd()
21
Return a string representing the current working directory.
os.getcwdu()
22
Return a Unicode object representing the current working directory.
22
Pyth
os.isatty(fd)
23 Return True if the file descriptor fd is open and connected to a tty(-like) device,
else False.
os.lchflags(path, flags)
24 Set the flags of path to the numeric flags, like chflags(), but do not follow
symbolic links.
os.lchmod(path, mode)
25
Change the mode of path to the numeric mode.
os.link(src, dst)
27
Create a hard link pointing to src named dst.
os.listdir(path)
28
Return a list containing the names of the entries in the directory given by path.
os.lstat(path)
30
Like stat(), but do not follow symbolic links.
os.major(device)
31
Extract the device major number from a raw device number.
os.makedev(major, minor)
32
Compose a raw device number from the major and minor device numbers.
os.makedirs(path[, mode])
33
Recursive directory creation function.
os.minor(device)
34
Extract the device minor number from a raw device number .
os.mkdir(path[, mode])
35
Create a directory named path with numeric mode mode.
22
Pyth
os.mkfifo(path[, mode])
36 Create a FIFO (a named pipe) named path with numeric mode mode. The
default mode is 0666 (octal).
os.openpty()
39 Open a new pseudo-terminal pair. Return a pair of file descriptors (master,
slave) for the pty and the tty, respectively.
os.pathconf(path, name)
40
Return system configuration information relevant to a named file.
os.pipe()
41 Create a pipe. Return a pair of file descriptors (r, w) usable for reading and
writing, respectively.
os.read(fd, n)
Read at most n bytes from file descriptor fd. Return a string containing the
43
bytes read. If the end of the file referred to by fd has been reached, an empty
string is returned.
os.readlink(path)
44
Return a string representing the path to which the symbolic link points.
os.remove(path)
45
Remove the file path.
os.removedirs(path)
46
Remove directories recursively.
os.rename(src, dst)
47
Rename the file or directory src to dst.
23
Pyth
os.renames(old, new)
48
Recursive directory or file renaming function.
os.rmdir(path)
49
Remove the directory path
os.stat(path)
50
Perform a stat system call on the given path.
os.stat_float_times([newvalue])
51
Determine whether stat_result represents time stamps as float objects.
os.statvfs(path)
52
Perform a statvfs system call on the given path.
os.symlink(src, dst)
53
Create a symbolic link pointing to src named dst.
os.tcgetpgrp(fd)
54 Return the process group associated with the terminal given by fd (an open file
descriptor as returned by open()).
os.tcsetpgrp(fd, pg)
55 Set the process group associated with the terminal given by fd (an open file
descriptor as returned by open()) to pg.
os.tempnam([dir[, prefix]])
56
Return a unique path name that is reasonable for creating a temporary file.
os.tmpfile()
57
Return a new file object opened in update mode (w+b).
os.tmpnam()
58
Return a unique path name that is reasonable for creating a temporary file.
os.ttyname(fd)
Return a string which specifies the terminal device associated with file
59
descriptor fd. If fd is not associated with a terminal device, an exception is
raised.
os.unlink(path)
60
Remove the file path.
23
Pyth
os.utime(path, times)
61
Set the access and modified times of the file specified by path.
os.write(fd, str)
63 Write the string str to file descriptor fd. Return the number of bytes actually
written.
23
17. Python ─ Exceptions Pyth
Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them:
ArithmeticError Base class for all errors that occur for numeric calculation.
23
Pyth
KeyError Raised when the specified key is not found in the dictionary.
Base class for all exceptions that occur outside the Python
EnvironmentError
environment.
Raised when the built-in function for a data type has the
ValueError valid type of arguments, but the arguments have invalid
values specified.
23
Pyth
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.
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:
23
Pyth
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
What is Exception?
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python
script 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.
23
Pyth
Syntax
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the
else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's
protection.
Example
This example opens a file, writes content in the, file and comes out 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"
23
Pyth
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"
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this
kind of try-except statement is not considered a good programming practice though,
23
Pyth
because it catches all exceptions but does not make the programmer identify the
root cause of the problem that may occur.
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but not both. You
cannot use else clause as well along with a finally clause.
Example
23
Pyth
#!/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:
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the except statements if present in the
next higher layer of the try-except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by exception.
You can capture an exception's argument by supplying a variable in the except
clause as follows:
try:
You do your operations here;
24
Pyth
......................
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
Raising an Exception
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.
Syntax
24
Pyth
Here, Exception is the type of exception (For example, NameError) and argument is
a value for the exception argument. The argument is optional; if not supplied, the
exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if
present, is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the
Python core raises are classes, with an argument that is an instance of the class.
Defining new exceptions is quite easy and can be done as follows:
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.
24
Pyth
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
24
18. Python ─ Classes and Objects Pyth
24
Pyth
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
Example
Following is the example of a simple Python class:
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
24
Pyth
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.
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
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
24
Pyth
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
You can add, remove, or modify attributes of classes and objects at any time:
Instead of using the normal statements to access attributes, you can use the
following functions:
24
Pyth
bases : A possibly empty tuple containing the base classes, in the order
of their occurrence in the base class list.
For the above class let us try to access all these attributes:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
24
Pyth
Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the
number of aliases that point to it changes.
24
Pyth
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.
25
Pyth
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:
Example
#!/usr/bin/python
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
25
Pyth
def childMethod(self):
print 'Calling child method'
Similar way, you can drive a class from multiple parent classes as follows:
25
Pyth
Example
#!/usr/bin/python
del ( self )
2 Destructor, deletes an object
Sample Call : del obj
repr ( self )
3 Evaluatable string representation
Sample Call : repr(obj)
25
Pyth
str ( self )
4 Printable string representation
Sample Call : str(obj)
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
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
25
Pyth
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible outside the class definition. You
need to name attributes with a double underscore prefix, and those attributes then
are not 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
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter. secretCount
AttributeError: JustCounter instance has no attribute ' secretCount'
Python protects those members by internally changing the name to include the
class 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
25
Pyth
1
2
2
25
19. Python ─ Regular Expressions Pyth
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'.
Parameter Description
You can specify different flags using bitwise OR (|). These are
flags
modifiers, which are listed in the table below.
25
Pyth
group(num=0) This method returns entire match (or specific subgroup num)
Example
#!/usr/bin/python
import re
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
25
Pyth
Parameter Description
You can specify different flags using bitwise OR (|). These are
flags
modifiers, which are listed in the table below.
The re.search function returns a match object on success, none on failure. We use
group(num) or groups() function of match object to get matched expression.
Match Object
Description
Methods
group(num=0) This method returns entire match (or specific subgroup num).
Example
#!/usr/bin/python
import re
25
Pyth
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
26
Pyth
No match!!
search --> matchObj.group() : dogs
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl,
substituting all occurrences unless max provided. This method returns modified
string.
Example
#!/usr/bin/python
import re
Modifier Description
Makes $ match the end of a line (not just the end of the string) and
re.M
makes ^ match the start of any line (not just the start of the
string).
re.S Makes a period (dot) match any character, including a newline.
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
26
Pyth
a| b Matches either a or b.
(?#...) Comment.
26
Pyth
(?! re) Specifies position using pattern negation. Does not have a range.
\S Matches non-whitespace.
\D Matches non-digits.
26
Pyth
Regular-Expression Examples
Literal characters
Example Description
Character classes
Example Description
26
Pyth
Repetition Cases
Example Description
Nongreedy repetition
This matches the smallest number of repetitions:
Example Description
26
Pyth
Backreferences
This matches a previously matched group again:
Example Description
Alternatives
Example Description
26
Pyth
Anchors
This needs to specify match position.
Example Description
26
Pyth
26
20. Python ─ CGI Programming Pyth
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.
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.
27
Pyth
CGI Architecture
The CGI architecture is as follows:
By default, the Linux server is configured to run only the scripts in the cgi-bin
directory in /var/www. If you want to specify any other directory to run your CGI
scripts, comment the following lines in the httpd.conf file:
27
Pyth
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
Here, we assume that you have Web Server up and running successfully and you
are able to run any other CGI program like Perl or Shell, etc.
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'
27
Pyth
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 Content-type: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:
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
27
Pyth
HTTP_COOKIE Returns the set cookies in the form of key & value pair.
27
Pyth
SERVER_SOFTWARE The name and version of the software the server is running.
Here is a small CGI program to list out all the CGI variables. Click this link to see
the result Get Environment
#!/usr/bin/python
import os
27
Pyth
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box.
Never use GET method if you have password or other sensitive information to pass
to the server. The GET method has size 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.
Below is hello_get.py script to handle input given by web browser. We are going
to use cgi module, which makes it very easy to access passed information:
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print "<html>"
27
Pyth
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Here is the actual output of the above form, you enter First and Last Name and then
click submit button to see the result.
First Name:
Submit
Last Name:
Bottom of Form
27
Pyth
#!/usr/bin/python
# Create instance of
FieldStorage form =
cgi.FieldStorage()
print "Content-type:text/html\r\n\r\
n" print "<html>"
print "<head>"
print "<title>Hello - Second CGI
Program</title>" print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name,
last_name) print "</body>"
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
2
Pyth
Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.
Fir Nam
Sub
Last Name: mit
Bottom of
Form
selected. Here is example HTML code for a form with two checkboxes:
Bottom of Form
Below is checkbox.cgi script to handle input
given by browser for
button.
#!/usr/bin/python
# Create instance of
FieldStorage form =
cgi.FieldStorage()
2
Pyth
if form.getvalue('maths'):
math_flag = "ON"
else:
math_flag = "OFF"
if form.getvalue('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % math_flag
print "<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"
Here is example HTML code for a form with two radio buttons:
28
Pyth
Submit
Maths Physics
Bottom of Form
Below is radiobutton.py script to handle input given by web browser for radio button:
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
28
Pyth
Submit
Bottom of Form
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
28
Pyth
Here is example HTML code for a form with one drop down box:
Bottom of Form
#!/usr/bin/python
28
Pyth
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
In many situations, using cookies is the most efficient method of remembering and
tracking preferences, purchases, commissions, and other information required for
better visitor experience or site statistics.
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.
Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
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.
28
Pyth
Name=Value: Cookies are set and retrieved in the form of key and value
pairs.
#!/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"
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....
2
Pyth
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
<html>
<body>
<form enctype="multipart/form-data"
action="save_file.py" method="post">
<p>File: <input type="file" name="filename" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
File:
Reset
Bottom of Form
28
Pyth
Above example has been disabled intentionally to save people uploading file on our
server, but you can try above code with your server.
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
28
Pyth
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("\\", "/" ))
For example, if you want make a FileName file downloadable from a given link,
then its syntax is as follows:
#!/usr/bin/python
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
str = fo.read();
print str
28
21. Python ─ Database Access Pyth
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:
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.
28
Pyth
#!/usr/bin/python
import MySQLdb
If it produces the following result, then it means MySQLdb module is not installed:
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:
29
Pyth
Example
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python
import MySQLdb
While running this script, it is producing the following result in my Linux machine.
29
Pyth
Example
Let us create Database table EMPLOYEE:
#!/usr/bin/python
import MySQLdb
cursor.execute(sql)
29
Pyth
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
29
Pyth
#!/usr/bin/python
import MySQLdb
Example
Following code segment is another form of execution where you can pass
parameters directly:
..................................
user_id = "test123"
password = "password"
29
Pyth
(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 fetch 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 querries all the records from EMPLOYEE table having salary
more than 1000:
#!/usr/bin/python
import MySQLdb
29
Pyth
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
29
Pyth
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
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
29
Pyth
Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the
following four properties:
Example
You already know how to implement transactions. Here is again similar example:
29
Pyth
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.
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.
db.rollback()
Disconnecting Database
To disconnect Database connection, use close() method.
29
Pyth
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 Er ors
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
30
Pyth
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.
30
22. Python ─ Network Programming Pyth
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.
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.
Term Description
30
Pyth
Each server listens for clients calling on one or more ports. A port
port may be a Fixnum port number, a string containing a port
number, or the name of a service.
Once you have socket object, then you can use required functions to create your
client or server program. Following is the list of functions required:
30
Pyth
A Simple Server
To write Internet servers, we use the socket function available in socket module to
create a socket object. A socket object is then used to call other functions to setup
a socket server.
Now call bind(hostname, port) function to specify a port for your service on the
given host.
Next, call the accept method of the returned object. This method waits until a client
connects to the port you specified, and then returns a connection object that
represents the connection to that client.
30
Pyth
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 socketmodule function.
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:
s.connect((host, port))
30
Pyth
print s.recv(1024)
s.close # Close the socket when done
Now run this server.py in background and then run above client.py to see the result.
$ python client.py
30
Pyth
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:
30
23. Python ─ Sending Email Pyth
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]]] )
host: This is the host running your SMTP server. You can specify IP address
of the host or a domain name like tutorialspoint.com. This is optional
argument.
port: If you are providing host argument, then you need to specify a port,
where SMTP server is listening. Usually this port would be 25.
An SMTP object has an instance method called sendmail, which is typically used to
do the work of mailing a message. It takes three parameters:
Example
Here is a simple way to send one e-mail using Python script. Try it once:
30
#!/usr/bin/python
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
30
Pyth
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 (even though the from and to
addresses are within the e-mail itself, these aren't always used to route mail).
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 (such as Hotmail or Yahoo! 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)
While sending an e-mail message, you can specify a Mime version, content type,
and character set to send an HTML e-mail.
Exampl
30
Pyth
#!/usr/bin/python
import smtplib
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
A boundary is started with two hyphens followed by a unique number, which cannot
appear in the message part of the e-mail. A final boundary denoting the e-mail's
final section must also end with two hyphens.
Attached files should be encoded with the pack("m") function to have base64
encoding before transmission.
Exampl
31
Pyth
#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
sender = '[email protected]'
reciever = '[email protected]'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
31
Pyth
%s
--%s
""" % (body,marker)
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
31
24. Python ─ Multithreading Pyth
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.
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
31
Pyth
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
while 1:
pass
Although it is very effective for low-level threading, but the thread module is very
limited compared to the newer threading module.
31
Pyth
The threading module exposes all the methods of the thread module and provides
some additional methods:
In addition to the methods, the threading module has the Thread class that
implements threading. The methods provided by the Thread class are as follows:
Once you have created the new Thread subclass, you can create an instance of it
and then start a new thread by invoking the start(), which in turn calls run()
method.
Example
#!/usr/bin/python
import threading
31
Pyth
import time
exitFlag = 0
Starting Thread-1
Starting Thread-2
31
Pyth
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
theLock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force threads to run
synchronously. The optional blocking parameter enables you to control whether the
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
31
Pyth
threadLock = threading.Lock()
threads = []
31
Pyth
t.join()
print "Exiting Main Thread"
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
get(): The get() removes and returns an item from the queue.
qsize() : The qsize() returns the number of items that are currently in the
queue.
Example
#!/usr/bin/python
31
Pyth
import Queue
import threading
import time
exitFlag = 0
32
Pyth
Starting Thread-1
Starting Thread-2
32
Pyth
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
32
25. Python ─ XML Processing Pyth
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.
The two most basic and broadly used APIs to XML data are the SAX and DOM
interfaces.
Simple API for XML (SAX) : Here, you register callbacks for events of
interest and then let the parser proceed through the document. This is useful
when your documents are large or you have memory limitations, it parses
the file as it reads it from disk and the entire file is never stored in memory.
SAX obviously cannot process information as fast as DOM can when working with
large files. On the other hand, using DOM exclusively can really kill your resources,
especially if used on a lot of small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two
different APIs literally complement each other, there is no reason why you can not
use them both for large projects.
32
Pyth
For all our XML code examples, let's use a simple XML file movies.xml as an
input:
32
Pyth
Your ContentHandler handles the particular tags and attributes of your flavor(s) of
XML. A ContentHandler object provides methods to handle various parsing events.
Its owning parser calls ContentHandler methods as it parses the XML file.
The methods startDocument and endDocument are called at the start and the end
of the XML file. The method characters(text) is passed character data of the XML
file via the parameter text.
The ContentHandler is called at the start and end of each element. If the parser is
not in namespace mode, the methods startElement(tag, attributes) and
endElement(tag) are called; otherwise, the corresponding methods startElementNS
and endElementNS are called. Here, tag is the element tag, and attributes is an
Attributes object.
xml.sax.make_parser( [parser_list] )
32
Pyth
Example
#!/usr/bin/python
import xml.sax
32
Pyth
32
Pyth
parser.parse("movies.xml")
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
32
Pyth
Stars: 2
Description: Viewable boredom
For a complete detail on SAX API documentation, please refer to standard Python SAX
APIs.
The DOM is extremely useful for random-access applications. SAX only allows you a
view of one bit of the document at a time. If you are looking at one SAX element,
you have no access to another.
Here is the easiest way to quickly load an XML document and to create a minidom
object using the xml.dom module. The minidom object provides a simple parser
method that quickly creates a DOM tree from the XML file.
The sample phrase calls the parse( file [,parser] ) function of the minidom object to
parse the XML file designated by file into a DOM tree object.
#!/usr/bin/python
32
Pyth
type = movie.getElementsByTagName('type')[0]
print "Type: %s" % type.childNodes[0].data
format = movie.getElementsByTagName('format')[0]
print "Format: %s" % format.childNodes[0].data
rating = movie.getElementsByTagName('rating')[0]
print "Rating: %s" % rating.childNodes[0].data
description = movie.getElementsByTagName('description')[0]
print "Description: %s" % description.childNodes[0].data
33
Pyth
Rating: PG
Description: Viewable boredom
For a complete detail on DOM API documentation, please refer to standard Python
DOM APIs.
33
26. Python ─ GUI Programming Pyth
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.
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:
Example
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
33
Pyth
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 Description
33
Pyth
33
Pyth
But on
The Button widget is used to add buttons in a Python application. These buttons can
display text or images that convey the purpose of the buttons. You can attach a
function or a method to a button which is called automatically when you click the
button.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
33
Pyth
highlightcolor The color of the focus highlight when the widget has focus.
Relief specifies the type of the border. Some of the values are
relief
SUNKEN, RAISED, GROOVE, and RIDGE.
Set this option to DISABLED to gray out the button and make
state it unresponsive. Has the value ACTIVE when the mouse is
over it. Default is NORMAL.
33
Pyth
Methods
Following are commonly used methods for this widget:
Medthod Description
Calls the button's callback, and returns what that function returns.
invoke()
Has no effect if the button is disabled or there is no callback.
Example
Try the following example yourself:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B.pack()
top.mainloop()
33
Pyth
Canvas
The Canvas is a rectangular area intended for drawing pictures or other complex
layouts. You can place graphics, text, widgets2. or frames on a Canvas.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
cursor Cursor used in the canvas like arrow, circle, dot etc.
Relief specifies the type of the border. Some of the values are
relief
SUNKEN, RAISED, GROOVE, and RIDGE.
33
Pyth
arc . Creates an arc item, which can be a chord, a pieslice or a simple arc.
oval . Creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for the
oval.
polygon . Creates a polygon item that must have at least three vertices.
33
Pyth
Example
Try the following example yourself:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
C.pack()
top.mainloop()
Checkbut on
The Checkbutton widget is used to display a number of options to a user as toggle
buttons. The user can then select one or more options by clicking the button
corresponding to each option.
34
Pyth
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
If you set this option to a cursor name (arrow, dot etc.), the
cursor mouse cursor will change to that pattern when it is over the
checkbutton.
34
Pyth
The color of the focus highlight when the checkbutton has the
highlightcolor
focus.
34
Pyth
Normally, lines are not wrapped. You can set this option to a
wraplength number of characters and all lines will be broken into pieces
no longer than that number.
Methods
Following are commonly used methods for this widget:
Medthod Description
You can call this method to get the same actions that would occur
invoke()
if the user clicked on the checkbutton to change its state.
34
Pyth
Example
Try the following example yourself:
top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
Entry
The Entry widget is used to accept single-line text strings from a user.
34
Pyth
If you want to display multiple lines of text that can be edited, then you
should use the Text widget.
If you want to display one or more lines of text that cannot be modified by
the user, then you should use the Label widget.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
If you set this option to a cursor name (arrow, dot etc.), the
cursor mouse cursor will change to that pattern when it is over the
checkbutton.
34
Pyth
The color of the focus highlight when the checkbutton has the
highlightcolor
focus.
If the text contains multiple lines, this option controls how the
justify
text is justified: CENTER, LEFT, or RIGHT.
If you expect that users will often enter more text than the
xscrollcommand onscreen size of the widget, you can link your entry widget to
a scrollbar.
Methods
34
Pyth
Medthod Description
select_range ( start, end ) Sets the selection under program control. Selects
the text starting at the start index, up to but not
34
Pyth
Example
Try the following example yourself:
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
34
Pyth
Frame
The Frame widget is very important for the process of grouping and organizing
other widgets in a somehow friendly way. It works like a container, which is
responsible for arranging the position of other widgets.
It uses rectangular areas in the screen to organize the layout and to provide
padding of these widgets. A frame can also be used as a foundation class to
implement complex widgets.
Syntax
Here is the simple syntax to create this widget:
Parameters:
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
34
Pyth
Color of the focus highlight when the frame does not have
highlightbackground
focus.
Color shown in the focus highlight when the frame has the
highlightcolor
focus.
Example
Try the following example yourself:
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
35
Pyth
root.mainloop()
Label
This widget implements a display box where you can place text or images. The text
displayed by this widget can be updated at any time you want.
It is also possible to underline part of the text (like to identify a keyboard shortcut)
and span the text across multiple lines.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
35
Pyth
Set this option equal to a bitmap or image object and the label will
bitmap
display that graphic.
If you set this option to a cursor name (arrow, dot etc.), the
cursor
mouse cursor will change to that pattern when it is over the
checkbutton.
If you are displaying text in this label (with the text or
font textvariable option, the font option specifies in what font that
text will be displayed.
Extra space added to the left and right of the text within the
padx
widget. Default is 1.
Extra space added above and below the text within the widget.
pady
Default is 1.
35
Pyth
You can display an underline (_) below the nth letter of the text,
underline counting from 0, by setting this option to n. The default is
underline=-1, which means no underlining.
You can limit the number of characters in each line by setting this
wraplength option to the desired number. The default value, 0, means that
lines will be broken only at newlines.
Example
Try the following example yourself:
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
35
Pyth
Listbox
The Listbox widget is used to display a list of items from which a user can select a
number of items
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
Color shown in the focus highlight when the widget has the
highlightcolor
focus.
35
Pyth
selectmode SINGLE: You can only select one line, and you can't drag the
mouse.wherever you click button 1, that line is selected.
Methods
Methods on listbox objects include:
Option Description
35
Pyth
35
Pyth
Example
Try the following example yourself:
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
35
Pyth
MenuBut on
A menubutton is the part of a drop-down menu that stays on the screen all the
time. Every menubutton is associated with a Menu widget that can display the
choices for that menubutton when the user clicks on it.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
35
Pyth
Color shown in the focus highlight when the widget has the
highlightcolor
focus.
justify This option controls where the text is located when the text
doesn't fill the menubutton: use justify=LEFT to left-justify
35
Pyth
How much space to leave to the left and right of the text of
padx
the menubutton. Default is 1.
How much space to leave above and below the text of the
pady
menubutton. Default is 1.
36
Pyth
Normally, lines are not wrapped. You can set this option to a
wraplength number of characters and all lines will be broken into pieces
no longer than that number.
Example
Try the following example yourself:
top = Tk()
mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton ( label="mayo",
variable=mayoVar )
mb.menu.add_checkbutton ( label="ketchup",
variable=ketchVar )
mb.pack()
top.mainloop()
36
Pyth
Menu
The goal of this widget is to allow us to create all kinds of menus that can be used
by our applications. The core functionality provides ways to create three menu
types: pop-up, toplevel and pull-down.
It is also possible to use other extended widgets to implement new types of menus,
such as the OptionMenu widget, which implements a special type that generates a
pop-up list of items within a selection.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
36
Pyth
The cursor that appears when the mouse is over the choices,
cursor
but only when the menu has been torn off.
disabledforeground The color of the text for items whose state is DISABLED.
fg The foreground color used for choices not under the mouse.
36
Pyth
Methods
These methods are available on Menu objects:
Option Description
add( type, options ) Adds a specific type of menu item to the menu.
36
Pyth
Example
Try the following example yourself:
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
editmenu.add_separator()
editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
36
Pyth
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)
root.mainloop()
Message
This widget provides a multiline and noneditable object that displays texts,
automatically breaking lines and justifying their contents.
Its functionality is very similar to the one provided by the Label widget, except that
it can also automatically wrap the text, maintaining a given width or aspect ratio.
Syntax
Here is the simple syntax to create this widget:
Parameters
1. master: This represents the parent window.
2. options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
36
Pyth
Option Description
Set this option equal to a bitmap or image object and the label will
bitmap
display that graphic.
If you set this option to a cursor name (arrow, dot etc.), the
cursor
mouse cursor will change to that pattern when it is over the
checkbutton.
If you are displaying text in this label (with the text or
font textvariable option, the font option specifies in what font that
text will be displayed.
Extra space added to the left and right of the text within the
padx
widget. Default is 1.
36
Pyth
Extra space added above and below the text within the widget.
pady
Default is 1.
You can display an underline (_) below the nth letter of the text,
underline counting from 0, by setting this option to n. The default is
underline=-1, which means no underlining.
You can limit the number of characters in each line by setting this
wraplength option to the desired number. The default value, 0, means that
lines will be broken only at newlines.
Example
Try the following example yourself:
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
36
Pyth
Radiobut on
This widget implements a multiple-choice button, which is a way to offer many
possible selections to the user and lets user choose only one of them.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
36
Pyth
37
Pyth
You can display an underline (_) below the nth letter of the
underline text, counting from 0, by setting this option to n. The
default is underline=-1, which means no underlining.
37
Pyth
Methods
Methods Description
Flashes the radiobutton a few times between its active and normal
flash()
colors, but leaves it the way it started.
You can call this method to get the same actions that would occur
invoke()
if the user clicked on the radiobutton to change its state.
Example:
Try the following example yourself:
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
37
Pyth
label = Label(root)
label.pack()
root.mainloop()
Scale
The Scale widget provides a graphical slider object that allows you to select values
from a specific scale.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
activebackground The background color when the mouse is over the scale.
37
Pyth
fg The color of the text used for the label and annotations.
The color of the focus highlight when the scale does not
highlightbackground
have focus.
highlightcolor The color of the focus highlight when the scale has the
focus.
You can display a label within the scale widget by setting
this option to the label's text. The label appears in the top
label
left corner if the scale is horizontal, or the top right corner
if vertical. The default is no label.
37
Pyth
37
Pyth
Methods
Scale objects have these methods:
Methods Description
37
Pyth
Example
Try the following example yourself:
def sel():
selection = "Value = " + str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()
37
Pyth
Scrol bar
This widget provides a slide controller that is used to implement vertical scrolled
widgets, such as Listbox, Text and Canvas. Note that you can also create horizontal
scrollbars on Entry widgets.
Syntax:
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
37
Pyth
The color of the focus highlight when the scrollbar does not
highlightbackground
have focus.
The color of the focus highlight when the scrollbar has the
highlightcolor
focus.
repeatinterval repeatinterval
37
Pyth
Methods
Scrollbar objects have these methods:
Methods Description
Example
Try the following example yourself:
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )
mainloop()
38
Pyth
Text
Text widgets provide advanced capabilities that allow you to edit a multiline text
and format the way it has to be displayed, such as changing its color and font.
You can also use elegant structures like tabs and marks to locate specific sections
of the text, and apply changes to those areas. Moreover, you can embed windows
and images in the text because this widget was designed to handle both plain and
formatted text.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
38
Pyth
The cursor that will appear when the mouse is over the text
cursor
widget.
font The default font for text inserted into the widget.
The color used for text (and bitmaps) within the widget.
fg You can change the color for tagged regions; this option is
just the default.
The color of the focus highlight when the text widget does
highlightbackground
not have focus.
The color of the focus highlight when the text widget has
highlightcolor
the focus.
38
Pyth
The size of the internal padding added to the left and right
padx
of the text area. Default is one pixel.
The size of the internal padding added above and below the
pady
text area. Default is one pixel.
38
Pyth
This option controls the display of lines that are too wide.
Set wrap=WORD and it will break the line after the last
wrap
word that will fit. With the default behavior, wrap=CHAR,
any line that gets too long will be broken at any character.
Methods
Text objects have these methods:
delete(startindex [,endindex])
This method deletes a specific character or a range of text.
get(startindex [,endindex])
This method returns a specific character or a range of text.
index(index)
Returns the absolute value of an index based on the given index.
insert(index [,string]...)
This method inserts strings at the specified index location.
see(index)
This method returns true if the text located at the index position is visible.
38
Pyth
Text widgets support three distinct helper structures: Marks, Tabs, and Indexes:
Marks are used to bookmark positions between two characters within a given text.
We have the following methods available when handling marks:
index(mark)
Returns the line and column location of a specific mark.
mark_gravity(mark [,gravity])
Returns the gravity of the given mark. If the second argument is provided, the
gravity is set for the given mark.
mark_names()
Returns all marks from the Text widget.
mark_set(mark, index)
Informs a new position to the given mark.
mark_unset(mark)
Removes the given mark from the Text widget.
Tags are used to associate names to regions of text which makes easy the task of
modifying the display settings of specific text areas. Tags are also used to bind
event callbacks to specific ranges of text.
tag_config
You can use this method to configure the tag properties, which include,
justify(center, left, or right), tabs(this property has the same functionality of the
Text widget tabs's property), and underline(used to underline the tagged text).
38
Pyth
tag_delete(tagname)
This method is used to delete and remove a given tag.
Example
Try the following example yourself:
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.. . .")
text.insert(END, "Bye Bye.. . .")
text.pack()
38
Pyth
TopLevel
Toplevel widgets work as windows that are directly managed by the window
manager. They do not necessarily have a parent widget on top of them.
Syntax
Here is the simple syntax to create this widget:
Parameters:
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
cursor The cursor that appears when the mouse is in this window.
font The default font for text inserted into the widget.
The color used for text (and bitmaps) within the widget. You can
fg
change the color for tagged regions; this option is just the default.
38
Pyth
Methods
Toplevel objects have these methods:
deiconify()
Displays the window, after using either the iconify or the withdraw methods.
frame()
Returns a system-specific window identifier.
group(window)
Adds the window to the window group administered by the given window.
iconify()
Turns the window into an icon, without destroying it.
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
iconify()
Turns the window into an icon, without destroying it.
state()
Returns the current state of the window. Possible values are normal, iconic,
withdrawn and icon.
transient([master])
Turns the window into a temporary(transient) window for the given master or to
the window's parent, when no argument is given.
withdraw()
38
Pyth
maxsize(width, height)
Defines the maximum size for this window.
minsize(width, height)
Defines the minimum size for this window.
positionfrom(who)
Defines the position controller.
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
sizefrom(who)
Defines the size controller.
title(string)
Defines the window title.
Example
Try following example yourself:
root = Tk()
top = Toplevel()
top.mainloop()
38
Pyth
SpinBox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Option Description
39
Pyth
fg Text color.
39
Pyth
to See from.
Methods
Spinbox objects have these methods:
delete(startindex [,endindex])
This method deletes a specific character or a range of text.
get(startindex [,endindex])
This method returns a specific character or a range of text.
identify(x, y)
Identifies the widget element at the given location.
index(index)
Returns the absolute value of an index based on the given index.
39
Pyth
insert(index [,string]...)
This method inserts strings at the specified index location.
invoke(element)
Invokes a spinbox button.
Example
Try the following example yourself:
master = Tk()
mainloop()
PanelWindow
A PanedWindow is a container widget that may contain any number of panes,
arranged horizontally or vertically.
Each pane contains one widget and each pair of panes is separated by a moveable
(via mouse movements) sash. Moving a sash causes the widgets on either side of
the sash to be resized.
39
Pyth
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
The color of the slider and arrowheads when the mouse is not
bg
over them.
The width of the 3-d borders around the entire perimeter of the
trough, and also the width of the 3-d effects on the arrowheads
bd
and slider. Default is no border around the trough, and a 2-pixel
border around the arrowheads and slider.
borderwidth Default is 2.
cursor The cursor that appears when the mouse is over the window.
handlepad Default is 8.
handlesize Default is 8.
39
Pyth
sashwidth Default is 2.
Methods
PanedWindow objects have these methods:
add(child, options)
Adds a child window to the paned window.
get(startindex [,endindex])
This method returns a specific character or a range of text.
config(options)
Modifies one or more widget options. If no options are given, the method returns
a dictionary containing all current option values.
Example
Try the following example yourself. Here's how to create a 3-pane widget:
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)
39
Pyth
m2.add(top)
mainloop()
LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer
or container for complex window layouts.
This widget has the features of a frame plus the ability to display a label.
Syntax
Here is the simple syntax to create this widget:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
39
Pyth
Option Description
Color of the focus highlight when the frame does not have
highlightbackground
focus.
Color shown in the focus highlight when the frame has the
highlightcolor
focus.
39
Pyth
Example
Try the following example yourself. Here is how to create a labelframe widget:
root = Tk()
root.mainloop()
tkMessageBox
The tkMessageBox module is used to display message boxes in your applications.
This module provides a number of functions that you can use to display an
appropriate message.
Syntax
Here is the simple syntax to create this widget:
39
Pyth
Parameters
FunctionName: This is the name of the appropriate message box function.
title: This is the text to be displayed in the title bar of a message box.
options: options are alternative choices that you may use to tailor a standard
message box. Some of the options that you can use are default and parent. The
default option is used to specify the default button, such as ABORT, RETRY, or
IGNORE in the message box. The parent option is used to specify the window on top
of which the message box is to be displayed.
You could use one of the following functions with dialogue box:
showinfo()
showwarning()
showerror ()
askquestion()
askokcancel()
askyesno ()
askretrycancel ()
Example
Try the following example yourself:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def hello():
tkMessageBox.showinfo("Say Hello", "Hello World")
top.mainloop()
39
Pyth
Standard At ributes
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
Dimensions
Various lengths, widths, and other dimensions of widgets can be described in many
different units.
If you set a dimension to an integer, it is assumed to be in pixels.
You can specify units by setting a dimension to a string containing a number followed
by.
Character Description
c Centimeters
40
Pyth
i Inches
m Millimeters
Length Options
Tkinter expresses a length as an integer number of pixels. Here is the list of
common length options:
borderwidth: Width of the border which gives a three-dimensional look to the widget.
highlightthickness: Width of the highlight rectangle when the widget has focus.
padX padY: Extra space the widget requests from its layout manager beyond the
minimum the widget needs to display its contents in the x and y directions.
wraplength: Maximum line length for widgets that perform word wrapping.
underline: Index of the character to underline in the widget's text (0 is the first
character, 1 the second one, and so on).
Colors
Tkinter represents colors with strings. There are two general ways to specify colors
in Tkinter:
You can use a string specifying the proportion of red, green and blue in hexadecimal
digits. For example, "#fff" is white, "#000000" is black, "#000fff000" is pure green,
and "#00ffff" is pure cyan (green plus blue).
You can also use any locally defined standard color name. The colors "white",
"black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be
available.
40
Pyth
Color options
The common color options are:
activebackground: Background color for the widget when the widget is active.
activeforeground: Foreground color for the widget when the widget is active.
background: Background color for the widget. This can also be represented as bg.
disabledforeground: Foreground color for the widget when the widget is disabled.
foreground: Foreground color for the widget. This can also be represented as fg.
highlightcolor: Foreground color of the highlight region when the widget has focus.
Fonts
There may be up to three ways to specify type style.
Example
("Helvetica", "16") for a 16-point Helvetica regular.
("Times", "24", "bold italic") for a 24-point Times bold italic.
import tkFont
40
Pyth
Example
helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")
X Window Fonts
If you are running under the X Window System, you can use any of the X font names.
Anchors
Anchors are used to define where text is positioned relative to a reference point.
Here is list of possible constants, which can be used for Anchor attribute.
NW
N
NE
W
CENTER
E
SW
S
SE
For example, if you use CENTER as a text anchor, the text will be centered
horizontally and vertically around the reference point.
Anchor NW will position the text so that the reference point coincides with the
northwest (top left) corner of the box containing the text.
40
Pyth
Anchor W will center the text vertically around the reference point, with the left
edge of the text box passing through that point, and so on.
If you create a small widget inside a large frame and use the anchor=SE option, the
widget will be placed in the bottom right corner of the frame. If you used anchor=N
instead, the widget would be centered along the top edge.
Example
The anchor constants are shown in this diagram:
Relief styles
The relief style of a widget refers to certain simulated 3-D effects around the
outside of the widget. Here is a screenshot of a row of buttons exhibiting all the
possible relief styles:
Here is a list of possible constants which can be used for relief attribute.
FLAT
RAISED
SUNKEN
GROOVE
RIDGE
40
Pyth
Example
from Tkinter import *
import Tkinter
top = Tkinter.Tk()
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
40
Pyth
Bitmaps
This attribute to displays a bitmap. There are following type of bitmaps available:
"error"
"gray75"
"gray50"
"gray25"
"gray12"
"hourglass"
"info"
"questhead"
"question"
"warning"
Example
from Tkinter import *
import Tkinter
top = Tkinter.Tk()
40
Pyth
B5.pack()
top.mainloop()
Cursors
Python Tkinter supports quite a number of different mouse cursors available. The
exact graphic may vary according to your operating system.
"arrow"
"circle"
"clock"
"cross"
"dotbox"
"exchange"
"fleur"
"heart"
"heart"
"man"
"mouse"
"pirate"
40
Pyth
"plus"
"shuttle"
"sizing"
"spider"
"spraycan"
"star"
"target"
"tcross"
"trek"
"watch"
Example
Try the following example by moving cursor on different buttons:
top = Tkinter.Tk()
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.
40
Pyth
The place() Method -This geometry manager organizes widgets by placing them in
a specific position in the parent widget.
Syntax
widget.pack( pack_options )
fill: Determines whether widget fills any extra space allocated to it by the packer, or
keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill
only vertically), or BOTH (fill both horizontally and vertically).
side: Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.
Example
Try the following example by moving cursor on different buttons:
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
40
Pyth
root.mainloop()
ipadx, ipady : How many pixels to pad widget, horizontally and vertically, inside
widget's borders.
padx, pady : How many pixels to pad widget, horizontally and vertically, outside v's
borders.
row: The row to put widget in; default the first row that is still empty.
sticky : What to do if the cell is larger than widget. By default, with sticky='', widget
is centered in its cell. sticky may be the string concatenation of zero or more of N, E,
S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of
the cell to which widget sticks.
41
Pyth
Example
Try the following example by moving cursor on different buttons:
import Tkinter
root = Tkinter.Tk( )
for r in range(3):
for c in range(4):
Tkinter.Label(root, text='R%s/C%s'%(r,c),
borderwidth=1 ).grid(row=r,column=c)
root.mainloop( )
This would produce the following result displaying 12 labels arrayed in a 3 x 4 grid:
Syntax
widget.place( place_options )
bordermode : INSIDE (the default) to indicate that other options refer to the
parent's inside (ignoring the parent's border); OUTSIDE otherwise.
relheight, relwidth : Height and width as a float between 0.0 and 1.0, as a fraction
of the height and width of the parent widget.
41
Pyth
relx, rely : Horizontal and vertical offset as a float between 0.0 and 1.0, as a
fraction of the height and width of the parent widget.
Example
Try the following example by moving cursor on different buttons:
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B.pack()
B.place(bordermode=OUTSIDE, height=100, width=100)
top.mainloop()
41
27. Python ─ Further Extensions Pyth
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."
Windows users get these headers as part of the package when they use the binary
Python installer.
Additionally, it is assumed that you have good knowledge of C or C++ to write any
Python Extension using C programming.
The C functions you want to expose as the interface from your module.
A table mapping the names of your functions as Python developers see them
to C functions inside the extension module.
An initialization function.
Make sure to include Python.h before any other headers you might need. You need
to follow the includes with the functions you want to call from Python.
41
Pyth
The C Functions
The signatures of the C implementation of your functions always takes one of the
following three forms:
Each one of the preceding declarations returns a Python object. There is no such
thing as avoid 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:
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.
41
Pyth
struct PyMethodDef
{ char *ml_name;
PyCFunction ml_meth;
int ml_flags;
char *ml_doc;
};
ml_meth: This must be the address to a function that has any one of the
signatures described in previous seection.
ml_flags: This tells the interpreter which of the three signatures ml_meth is
using.
o This can also have a value of METH_NOARGS that indicates you do not
want to accept any arguments.
ml_doc: This is the docstring for the function, which could be NULL if you do
not feel like writing one.
This table needs to be terminated with a sentinel that consists of NULL and 0 values
for the appropriate members.
41
Pyth
Example
For the above-defined function, we have following method mapping table:
The initialization function needs to be exported from the library you are building.
The Python headers define PyMODINIT_FUNC to include the appropriate
incantations for that to happen for the particular environment in which we're
compiling. All you have to do is use it when defining the function.
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
#include <Python.h>
41
Pyth
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
Example
A simple example that makes use of all the above concepts:
#include <Python.h>
void inithelloworld(void)
{
Py_InitModule3("helloworld", helloworld_funcs,
"Extension module example!");
}
Here the Py_BuildValue function is used to build a Python value. Save above code in
hello.c file. We would see how to compile and install this module to be called from
Python script.
41
Pyth
For the above module, you need to prepare following setup.py script:
Now, use the following command, which would perform all needed compilation and
linking steps, with the right compiler and linker commands and flags, and copies
the resulting dynamic library into an appropriate directory:
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()
41
Pyth
The method table containing an entry for the new function would look like this:
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.
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:
41
Pyth
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.
42
Pyth
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:
42
Pyth
You can return two values from your function as follows, this would be cauptured
using a list in Python.
42
Pyth
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.
42
Pyth
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}.
42