0% found this document useful (0 votes)
10 views

python notes

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum between 1985 and 1990. It features easy readability, a broad standard library, and supports various programming paradigms including functional and structured programming. Python allows for dynamic typing and automatic garbage collection, making it suitable for both beginners and experienced developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

python notes

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum between 1985 and 1990. It features easy readability, a broad standard library, and supports various programming paradigms including functional and structured programming. Python allows for dynamic typing and automatic garbage collection, making it suitable for both beginners and experienced developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Python is a general-purpose interpreted, interactive, object-oriented, and

high-level programming language. It was created by Guido van Rossum


during 1985- 1990. Like Perl, Python source code is also available under
the GNU General Public License (GPL)..
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:
print "Hello, Python!"

Python Overview
Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses
English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.
 Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented
style or technique of programming that encapsulates code within
objects.
 Python is a Beginner's Language: Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers to games.
History of Python
 Python was developed by Guido van Rossum in the late eighties and
early nineties at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
 Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other
scripting languages.
 Python is copyrighted. Like Perl, Python source code is now available
under the GNU General Public License (GPL).
 Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing its progress.
Python Features
Python's features include:
 Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the
language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the
eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
 Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
 Scalable: Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below:
 IT supports functional and structured programming methods as well
as OOP.
 It can be used as a scripting language or can be compiled to byte-code
for building large applications.
 It provides very high-level dynamic data types and supports dynamic
type checking.
 IT supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.

M1, mark1, mark_1u347873,_mark1,


Int, real, double, if, if_else ,
1m, mark.1,
001mark1
Mark1_001
Mark 1 , mark @1, total-123

Python Variable Types


 Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space
in memory.
 Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
 Therefore, by assigning different data types to variables, you can
store integers, decimals or characters in these variables.
Assigning Values to Variables
 Python variables do not need explicit declaration to reserve memory
space. The declaration happens automatically when you assign a
value to a variable. The equal sign (=) is used to assign values to
variables.
 The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in
the variable.
 For example −
#!/usr/bin/python

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables
are assigned to the same memory location. You can also assign multiple
objects to multiple variables. For example −
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a
and b respectively, and one string object with the value "john" is assigned
to the variable c.
Standard Data Types
The data stored in memory can be of many types. For example, a person's
age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method for
each of them.
Python has five standard data types −
 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 −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del
statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
 int (signed integers)
 long (long integers, they can also be represented in octal and
hexadecimal)
 float (floating point real values)
complex (complex numbers)

Examples
Here are some examples of numbers −
int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j


Python allows you to use a lowercase L with long, but it is

recommended that you use only an uppercase L to avoid confusion
with the number 1. Python displays long integers with an uppercase
L.
 A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are the real numbers and j
is the imaginary unit.
Python Strings
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows for either pairs of single
or double quotes. Subsets of strings can be taken using the slice operator ([
] and [:] ) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*)
is the repetition operator. For example −
#!/usr/bin/python

str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets
([]). To some extent, lists are similar to arrays in C. One difference between
them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and
[:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1. The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator. For example −
#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
The most basic data structure in Python is the sequence. Each element of
a sequence is assigned a number - its position or index. The first index is
zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are
lists and tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These
operations include indexing, slicing, adding, multiplying, and checking for
membership. In addition, Python has built-in functions for finding the
length of a sequence and for finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be
written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that items in a list need not be of
the same type.
Creating a list is as simple as putting different comma-separated values
between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index. For example −
#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0]


print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
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

list = ['physics', 'chemistry', 1997, 2000];

print "Value available at index 2 : "


print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Note: append() method is discussed in subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements
To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do
not know. For example −
#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];

print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Note: remove() method is discussed in subsequent section.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list,
not a string.
In fact, lists respond to all of the general sequence operations we used on
strings in the prior chapter.
Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', Repetition


'Hi!']

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print 123 Iteration


x,
Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for
lists as they do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']

Python Results Description


Expression

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections


Built-in List Functions & Methods:
Python includes the following list functions −
SN Function with Description

1 cmp(list1, list2)

Compares elements of both lists.


Description
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 numbers, perform numeric coercion if necessary and
compare.
 If either element is a number, then the other element is
"larger" (numbers are "smallest").
 Otherwise, types are sorted alphabetically by name.
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

list1, list2 = [123, 'xyz'], [456, 'abc']

print cmp(list1, list2)


print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
When we run above program, it produces following result −
-1
1
-1

2 len(list)

Gives the total length of the list.


Description
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

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']

print "First list length : ", len(list1)


print "Second list length : ", len(list2)
When we run above program, it produces following result −
First list length : 3
Second list length : 2

3 max(list)

Returns item from the list with max value.


Description
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
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]

print "Max value element : ", max(list1)


print "Max value element : ", max(list2)
When we run above program, it produces following result −
Max value element : zara
Max value element : 700

4 min(list)

Returns item from the list with min value.


Description
The method min() returns the elements from the list with
minimum value.
Syntax
Following is the syntax for min() method:
min(list)
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

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]

print "min value element : ", min(list1)


print "min value element : ", min(list2)
When we run above program, it produces following result −
min value element : 123
min value element : 200

5 list(seq)
Converts a tuple into list.
Description
The method list() takes sequence types and converts them to
lists. This is used to convert a given tuple into list.
Note: Tuple are very similar to lists with only difference that
element values of a tuple can not be changed and tuple elements
are put between parentheses instead of square bracket.
Syntax
Following is the syntax for list() method:
list( seq )
Parameters
 seq -- This is a tuple to be converted into list.
Return Value
This method returns the list.
Example
The following example shows the usage of list() method.
!/usr/bin/python

aTuple = (123, 'xyz', 'zara', 'abc');


aList = list(aTuple)

print "List elements : ", aList


When we run above program, it produces following result:
List elements : [123, 'xyz', 'zara', 'abc']

Python includes following list methods


SN Methods with Description

1 list.append(obj)

Appends object obj to list


Description
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

aList = [123, 'xyz', 'zara', 'abc'];


aList.append( 2009 );
print "Updated List : ", aList
When we run above program, it produces following result −
Updated List : [123, 'xyz', 'zara', 'abc', 2009]

2 list.count(obj)

Returns count of how many times obj occurs in list


Description
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

aList = [123, 'xyz', 'zara', 'abc', 123];

print "Count for 123 : ", aList.count(123)


print "Count for zara : ", aList.count('zara')
When we run above program, it produces following result −
Count for 123 : 2
Count for zara : 1

3 list.extend(seq)

Appends the contents of seq to list


Description
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

aList = [123, 'xyz', 'zara', 'abc', 123];


bList = [2009, 'manni'];
aList.extend(bList)

print "Extended List : ", aList


When we run above program, it produces following result −
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

4 list.index(obj)

Returns the lowest index in list that obj appears


Description
The method index() returns the lowest index in list
that obj appears.
Syntax
Following is the syntax for index() method −
list.index(obj)
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

aList = [123, 'xyz', 'zara', 'abc'];

print "Index for xyz : ", aList.index( 'xyz' )


print "Index for zara : ", aList.index( 'zara' )
When we run above program, it produces following result −
Index for xyz : 1
Index for zara : 2

5 list.insert(index, obj)

Inserts object obj into list at offset index

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

Python Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas lists
use square brackets.
Creating a tuple is as simple as putting different comma-separated values.
Optionally you can put these comma-separated values between
parentheses also. Tuples can be thought of as read-only lists. For
example −
For example –

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
This produce the following result −
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
The following code is invalid with tuple, because we attempted to update a
tuple, which is not allowed. Similar case is possible with lists −
#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma,
even though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Accessing Values in Tuples:
To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index. For example −
#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0]


print "tup2[1:5]: ", tup2[1:5]
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the
values of tuple elements. You are able to take portions of existing tuples to
create new tuples as the following example demonstrates −
#!/usr/bin/python

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course,
nothing wrong with putting together another tuple with the undesired
elements discarded.
To explicitly remove an entire tuple, just use the del statement. For
example:
#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);

print tup
del tup;
print "After deleting tup : "
print tup
This produces the following result. Note an exception raised, this is
because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple,
not a string.
In fact, tuples respond to all of the general sequence operations we used on
strings in the prior chapter −
Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', Repetition


'Hi!')

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print 123 Iteration


x,
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way for
tuples as they do for strings. Assuming following input −
L = ('spam', 'Spam', 'SPAM!')

Python Results Description


Expression

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections


No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying
symbols, i.e., brackets for lists, parentheses for tuples, etc., default to
tuples, as indicated in these short examples −
#!/usr/bin/python

print 'abc', -4.24e93, 18+6.6j, 'xyz'


x, y = 1, 2;
print "Value of x , y : ", x,y
When the above code is executed, it produces the following result −
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
Built-in Tuple Functions
Python includes the following tuple functions −
SN Function with Description

1 cmp(tuple1, tuple2)

Compares elements of both tuples.


Description
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 numbers, perform numeric coercion if necessary and
compare.
 If either element is a number, then the other element is
"larger" (numbers are "smallest").
 Otherwise, types are sorted alphabetically by name.
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.
Example
The following example shows the usage of cmp() method.
#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz'), (456, 'abc')

print cmp(tuple1, tuple2)


print cmp(tuple2, tuple1)
tuple3 = tuple2 + (786,);
print cmp(tuple2, tuple3)
When we run above program, it produces following result −
-1
1
-1

2 len(tuple)

Gives the total length of the tuple.


Description
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

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')

print "First tuple length : ", len(tuple1)


print "Second tuple length : ", len(tuple2)
When we run above program, it produces following result −
First tuple length : 3
Second tuple length : 2

3 max(tuple)

Returns item from the tuple with max value.


Description
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
tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)

print "Max value element : ", max(tuple1)


print "Max value element : ", max(tuple2)
When we run above program, it produces following result −
Max value element : zara
Max value element : 700

4 min(tuple)

Returns item from the tuple with min value.


Description
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

tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)

print "min value element : ", min(tuple1)


print "min value element : ", min(tuple2)
When we run above program, it produces following result −
min value element : 123
min value element : 200

5 tuple(seq)
Converts a list into tuple.
Description
The method tuple() converts a list of items into tuples
Syntax
Following is the syntax for tuple() method −
tuple( seq )
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

aList = (123, 'xyz', 'zara', 'abc');


aTuple = tuple(aList)

print "Tuple elements : ", aTuple


When we run above program, it produces following result −
Tuple elements : (123, 'xyz', 'zara', 'abc')

Python Dictionary
#!/usr/bin/python

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.
Example
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 produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to
say that the elements are "out of order"; they are simply unordered.

Accessing Values in Dictionary:


To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value. Following is a simple example −
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name']


print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
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

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice']


When the above code is executed, it produces the following result −
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 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry


dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result −
dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
operation.
To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example −
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # remove entry with key 'Name'


dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised
because after del dict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note: del() method is discussed in subsequent section.
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python
object, either standard objects or user-defined objects. However, same is
not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate
key is allowed. When duplicate keys encountered during assignment, the
last assignment wins. For example −
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict['Name']


When the above code is executed, it produces the following result −
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers
or tuples as dictionary keys but something like ['key'] is not allowed.
Following is a simple example:
#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7};

print "dict['Name']: ", dict['Name']


When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
Built-in Dictionary Functions & Methods −
Python includes the following dictionary functions −
SN Function with Description

1 cmp(dict1, dict2)
Compares elements of both dict.

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)
Produces a printable string representation of a dictionary

4 type(variable)
Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.
Python includes following dictionary methods −
SN Methods with Description

1 dict.clear()
Removes all elements of dictionary dict

2 dict.copy()
Returns a shallow copy of dictionary dict

3 dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.

4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary

5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise

6 dict.items()
Returns a list of dict's (key, value) tuple pairs

7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already
in dict

9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict

10 dict.values()
Returns list of dictionary dict's values

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in
types. To convert between types, you simply use the type name as a
function.
There are several built-in functions to perform conversion from one data
type to another. These functions return a new object representing the
converted value.
Function Description

int(x [,base]) Converts x to an integer. base specifies the base


if x is a string.

long(x [,base] ) Converts x to a long integer. base specifies the


base if x is a string.

float(x) Converts x to a floating-point number.

complex(real Creates a complex number.


[,imag])

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

tuple(s) Converts s to a tuple.

list(s) Converts s to a list.

set(s) Converts s to a set.


dict(d) Creates a dictionary. d must be a sequence of
(key,value) tuples.

frozenset(s) Converts s to a frozen set.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

Looping Techniques

When looping through a sequence, the position index and corresponding


value can be retrieved at the same time using the enumerate() function.

>>>

>>> for i, v in enumerate(['tic', 'tac', 'toe']):


... print i, v
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be
paired with the zip() function.

>>>

>>> questions = ['name', 'quest', 'favorite color']


>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your {0}? It is {1}.'.format(q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward


direction and then call the reversed() function.

>>>

>>> for i in reversed(xrange(1,10,2)):


... print i
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which
returns a new sorted list while leaving the source unaltered.

>>>

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']


>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear

When looping through dictionaries, the key and corresponding value can be
retrieved at the same time using the iteritems() method.

>>>

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}


>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave

Python Strings
Strings are amongst the most popular types in Python. We can create them
simply by enclosing characters in quotes. Python treats single quotes the
same as double quotes. Creating strings is as simple as assigning a value to
a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring. For example −
#!/usr/bin/python

var1 = 'Hello World!'


var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result −
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

var1 = 'Hello World!'

print "Updated String :- ", var1[:6] + 'Python'


When the above code is executed, it produces the following result −
Updated String :- Hello Python
Escape Characters
Following table is a list of escape or non-printable characters that can be
represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double
quoted strings.
Backslash Hexadecimal Description
notation character

\a 0x07 Bell or alert

\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

\nnn Octal notation, where n is in the


range 0.7

\r 0x0d Carriage return

\s 0x20 Space

\t 0x09 Tab

\v 0x0b Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is


in the range 0.9, a.f, or A.F
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then

Operator Description Example
+ Concatenation - Adds values on either side a + b will
of the operator give
HelloPython

* Repetition - Creates new strings, a*2 will give


concatenating multiple copies of the same -HelloHello
string

[] Slice - Gives the character from the given a[1] will give
index e

[:] Range Slice - Gives the characters from the a[1:4] will
given range give ell

in Membership - Returns true if a character H in a will


exists in the given string give 1

not in Membership - Returns true if a character M not in a


does not exist in the given string will give 1

r/R Raw String - Suppresses actual meaning of print r'\n'


Escape characters. The syntax for raw prints \n
strings is exactly the same as for normal and print
strings with the exception of the raw string R'\n'prints
operator, the letter "r," which precedes the \n
quotation marks. The "r" can be lowercase
(r) or uppercase (R) and must be placed
immediately preceding the first quote mark.

% Format - Performs String formatting See at next


section
String Formatting Operator
One of Python's coolest features is the string format operator %. This
operator is unique to strings and makes up for the pack of having functions
from C's printf() family. Following is a simple example −
#!/usr/bin/python

print "My name is %s and weight is %d kg!" % ('Zara', 21)


When the above code is executed, it produces the following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with %

Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E


Other supported symbols and functionality are listed in the following table

Symbol Functionality

* argument specifies width or precision

- left justification

+ display the sign

<sp> leave a blank space before a positive number

# add the octal leading zero ( '0' ) or hexadecimal


leading '0x' or '0X', depending on whether 'x' or
'X' were used.

0 pad from left with zeros (instead of spaces)

% '%%' leaves you with a single literal '%'

(var) mapping variable (dictionary arguments)

m.n. m is the minimum total width and n is the


number of digits to display after the decimal
point (if appl.)
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span
multiple lines, including verbatim NEWLINEs, TABs, and any other
special characters.
The syntax for triple quotes consists of three consecutive single or
doublequotes.
#!/usr/bin/python

para_str = """this is a long string that is made up of


several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str
When the above code is executed, it produces the following result. Note
how every single special character has been converted to its printed form,
right down to the last NEWLINE at the end of the string between the "up."
and closing triple quotes. Also note that NEWLINEs occur either with an
explicit carriage return at the end of a line or its escape code (\n) −
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
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!'


When the above code is executed, it produces the following result −
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the
prefix r.
Built-in Function
(i) Standard Type Functions
Cmp() it is one of the built-in function.it is use to
compare the string.(ASCII value-based) comparison.
Ex str1=’abc’
Str2=’xyz’
Cmp(str1,str2)
-11
Cmp(str2. ‘xyz’)
0
(ii) Sequence Type Functions
a) len() –it is a one of the built in function.it returns the
number of characters in the string
ex: str1=’lmn’
len(str1)
3
b) max() and min(). These are another sequence type built
in function .it returns the greatest and least characters
respectively.
Ex: min(‘abcd12’)
1
Min(“Abcad”)
A
c) enumerate()
ex s=’foobar’
for i, t in enumerate(s)
print I,t
output
0f
1o
2o
3b
4a
5r
d) zip
ex s, t=’foa’, ‘obr’
zip(s, t)
output
[(‘f’, ‘o’), (‘o’, ‘b’), (‘a’, ‘r’)]

iii) String type function


raw-input() – the built in raw-input() function prompts
the user with a given string and accepts and returns a
user-input string
ex: user_input=raw_input(“enter your name:”)
enter your name: stanns

Built-in String Methods


Python includes the following built-in methods to manipulate strings −
SN Methods with Description

1 capitalize()
Capitalizes first letter of string
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
str = "this is string example....wow!!!";

print "str.capitalize() : ", str.capitalize()


Result
str.capitalize() : This is string example....wow!!!

2 center(width, fillchar)

Returns a space-padded string with the original string centered to


a total of width columns.
The method center() returns centered in a string of length width.
Padding is done using the specified fillchar. Default filler is a
space.
Syntax
str.center(width[, fillchar])
Parameters
 width -- This is the total width of the string.
 fillchar -- This is the filler character.
Return Value
This method returns centered in a string of length width.
Example
The following example shows the usage of center() method.
#!/usr/bin/python

str = "this is string example....wow!!!";

print "str.center(40, 'a') : ", str.center(40, 'a')


Result
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa

3 count(str, beg= 0,end=len(string))

Counts how many times str occurs in string or in a substring of


string if starting index beg and ending index end are given.

4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding.
encoding defaults to the default string encoding.

5 encode(encoding='UTF-8',errors='strict')

Returns encoded string version of string; on error, default is to


raise a ValueError unless errors is given with 'ignore' or 'replace'.

6 endswith(suffix, beg=0, end=len(string))


Determines if string or a substring of string (if starting index beg
and ending index end are given) ends with suffix; returns true if
so and false otherwise.

7 expandtabs(tabsize=8)

Expands tabs in string to multiple spaces; defaults to 8 spaces per


tab if tabsize not provided.

8 find(str, beg=0 end=len(string))

Determine if str occurs in string or in a substring of string if


starting index beg and ending index end are given returns index if
found and -1 otherwise.

9 index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found.

10 isalnum()

Returns true if string has at least 1 character and all characters


are alphanumeric and false otherwise.

11 isalpha()

Returns true if string has at least 1 character and all characters


are alphabetic and false otherwise.

12 isdigit()

Returns true if string contains only digits and false otherwise.


13 islower()

Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

14 isnumeric()

Returns true if a unicode string contains only numeric characters


and false otherwise.

15 isspace()

Returns true if string contains only whitespace characters and


false otherwise.

16 istitle()

Returns true if string is properly "titlecased" and false otherwise.

17 isupper()

Returns true if string has at least one cased character and all
cased characters are in uppercase and false otherwise.

18 join(seq)

Merges (concatenates) the string representations of elements in


sequence seq into a string, with separator string.

19 len(string)

Returns the length of the string

20 ljust(width[, fillchar])

Returns a space-padded string with the original string left-


justified to a total of width columns.

21 lower()

Converts all uppercase letters in string to lowercase.


Description
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

str = "THIS IS STRING EXAMPLE....WOW!!!";

print str.lower()
When we run above program, it produces following result −
this is string example....wow!!!

22 lstrip()

Removes all leading whitespace in string.

23 maketrans()

Returns a translation table to be used in translate function.

24 max(str)

Returns the max alphabetical character from the string str.

25 min(str)

Returns the min alphabetical character from the string str.

26 replace(old, new [, max])


Replaces all occurrences of old in string with new or at most max
occurrences if max given.

27 rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string.

28 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string.

29 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-


justified to a total of width columns.

30 rstrip()

Removes all trailing whitespace of string.

31 split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and


returns list of substrings; split into at most num substrings if
given.

32 splitlines( num=string.count('\n'))

Splits string at all (or num) NEWLINEs and returns a list of each
line with NEWLINEs removed.

33 startswith(str, beg=0,end=len(string))

Determines if string or a substring of string (if starting index beg


and ending index end are given) starts with substring str; returns
true if so and false otherwise.

34 strip([chars])

Performs both lstrip() and rstrip() on string

35 swapcase()
Inverts case for all letters in string.

36 title()

Returns "titlecased" version of string, that is, all words begin with
uppercase and the rest are lowercase.

37 translate(table, deletechars="")

Translates string according to translation table str(256 chars),


removing those in the del string.

38 upper()

Converts lowercase letters in string to uppercase.

39 zfill (width)

Returns original string leftpadded with zeros to a total of width


characters; intended for numbers, zfill() retains any sign given
(less one zero).

40 isdecimal()

Returns true if a unicode string contains only decimal characters


and false otherwise.
Python Decision Making
Decision making is anticipation of conditions occurring while execution of
the program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome. You need to determine which action to take and which
statements to execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found
in most of the programming languages −
Python programming language assumes any non-zero and non-
null values as TRUE, and if it is either zero or null, then it is assumed as
FALSE value.
Python programming language provides following types of decision
making statements. Click the following links to check their detail.
Statement Description

if statements An if statement consists of a boolean


expression followed by one or more
statements.

if...else statements An if statement can be followed by an


optional else statement, which executes
when the boolean expression is FALSE.

nested if statements You can use one if or else if statement


inside another if or else if statement(s).
Let us go through each decision making briefly –
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

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!"
When the above code is executed, it produces the following result −
1 - Got a true expression value
100
Good bye!
IF...ELIF...ELSE Statements
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)
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
else:
print "2 - Got a false expression value"
print var2

print "Good bye!"


When the above code is executed, it produces the following result −
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
The elif Statement
The elif statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
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 ofelif 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 −
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

print "Good bye!"


When the above code is executed, it produces the following result −
3 - Got a true expression value
100
Good bye!
Python nested IF statements
There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the
nested ifconstruct.
In a nested if construct, you can have an if...elif...else construct inside
anotherif...elif...else construct.
Syntax:
The syntax of the nested if...elif...else construct may be:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example:
#!/usr/bin/python

var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"

print "Good bye!"


When the above code is executed, it produces following result:
Expression value is less than 200
Which is 100
Good bye!

Single Statement Suites


If the suite of an if clause consists only of a single line, it may go on the
same line as the header statement.
Here is an example of a one-line if clause −
#!/usr/bin/python

var = 100

if ( var == 100 ) : print "Value of expression is 100"

print "Good bye!"


When the above code is executed, it produces the following result −
Value of expression is 100
Good bye!
Python Loops
In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. There may be
a situation when you need to execute a block of code several number of
times.
Programming languages provide various control structures that allow for
more complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement −

Python programming language provides following types of loops to handle


looping requirements.
Loop Type Description

while loop Repeats a statement or group of statements while


a given condition is TRUE. It tests the condition
before executing the loop body.

for loop Executes a sequence of statements multiple times


and abbreviates the code that manages the loop
variable.

nested loops You can use one or more loop inside any another
while, for or do..while loop.

Python while Loop Statements


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)
Here, statement(s) may be a single statement or a block of statements.
Thecondition may be any expression, and true is any non-zero value. The
loop iterates while the condition is true.
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

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

print "Good bye!"


When the above code is executed, it produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
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.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You
must use caution when using while loops because of the possibility that
this condition never resolves to a FALSE value. This results in a loop that
never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the
server needs to run continuously so that client programs can communicate
with it as and when required.
#!/usr/bin/python

var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num

print "Good bye!"


When the above code is executed, it produces the following result −
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit
the program.
Using else Statement with Loops
Python supports to have an else statement associated with a loop
statement.
 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 while statement that prints a number as long as it is less than 5,
otherwise else statement gets executed.p>
#!/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"
When the above code is executed, it produces the following result −
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
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a
single statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −
#!/usr/bin/python

flag = 1

while (flag): print 'Given flag is really true!'

print "Good bye!"


It is better not try above example because it goes into infinite loop and you
need to press CTRL+C keys to exit.
Python for Loop Statements

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
toiterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.
Flow Diagram
Example
#!/usr/bin/python

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"


When the above code is executed, it produces the following result −
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!
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the
sequence itself. Following is a simple example −
#!/usr/bin/python

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"


When the above code is executed, it produces the following result −
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
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.
Using else Statement with Loops
Python supports to have an else statement associated with a loop
statement
 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

for num in range(10,20): #to iterate between 10 to 20


for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
When the above code is executed, it produces the following result −
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
Python 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

print "Good bye!"


When the above code is executed, it produces following result −
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!

The range() Function

If you do need to iterate over a sequence of numbers, the built-in


function range() comes in handy. It generates lists containing arithmetic
progressions:

>>>
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed(seq)
Return a reverse iterator. seq must be an object

Sorted() use to sort the element


enumerate(sequence, start=0)
Return an enumerate object. sequence must be a sequence,
an iterator, or some other object which supports iteration.
The next() method of the iterator returned by enumerate() returns
a tuple containing a count (from start which defaults to 0) and the
values obtained from iterating oversequence:

>>>
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Loop Control Statements


Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created in
that scope are destroyed.
Python supports the following control statements. Click the following links
to check their detail.
Control Statement Description

break statement Terminates the loop statement and transfers


execution to the statement immediately
following the loop.

continue statement Causes the loop to skip the remainder of its


body and immediately retest its condition
prior to reiterating.

pass statement The pass statement in Python is used when a


statement is required syntactically but you do
not want any command or code to execute.
Python 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
Flow Diagram

Example
#!/usr/bin/python

for letter in 'Python': # First Example


if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break

print "Good bye!"


When the above code is executed, it produces the following result −
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!

Python continue statement


It returns the control to the beginning of the while loop..
The continuestatement 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
Example
#!/usr/bin/python

for letter in 'Python': # First Example


if letter == 'h':
continue
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
When the above code is executed, it produces the following result −
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!
Python pass Statement
It is used when a statement is required syntactically but you do not want
any command or code to execute.
The pass statement is a null operation; nothing happens when it executes.
The pass is also useful in places where your code will eventually go, but
has not been written yet (e.g., in stubs for example):
Syntax
pass
Example
#!/usr/bin/python

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"


When the above code is executed, it produces following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Python Numbers
Number data types store numeric values. They are immutable data types,
means that changing the value of a number data type results in a newly
allocated object.
Number objects are created when you assign a value to them. For example

var1 = 1
var2 = 10
You can also delete the reference to a number object by using
the delstatement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using
the del statement. For example:
del var
del var_a, var_b
Python supports four different numerical types −
 int (signed integers): They are often called just integers or ints,
are positive or negative whole numbers with no decimal point.
 long (long integers ): Also called longs, they are integers of
unlimited size, written like integers and followed by an uppercase or
lowercase L.
 float (floating point real values) : Also called floats, they
represent real numbers and are written with a decimal point dividing
the integer and fractional parts. Floats may also be in scientific
notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 =
250).
 complex (complex numbers) : are of the form a + bJ, where a
and b are floats and J (or j) represents the square root of -1 (which is
an imaginary number). The real part of the number is a, and the
imaginary part is b. Complex numbers are not used much in Python
programming.
Examples
Here are some examples of numbers
int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j


080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j


 Python allows you to use a lowercase L with long, but it is
recommended that you use only an uppercase L to avoid confusion
with the number 1. Python displays long integers with an uppercase
L.
 A complex number consists of an ordered pair of real floating point
numbers denoted by a + bj, where a is the real part and b is the
imaginary part of the complex number.
Number Type Conversion
Python converts numbers internally in an expression containing mixed
types to a common type for evaluation. But sometimes, you need to coerce
a number explicitly from one type to another to satisfy the requirements of
an operator or function parameter.
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x
and imaginary part zero.
 Type complex(x, y) to convert x and y to a complex number with
real part x and imaginary part y. x and y are numeric expressions
Mathematical Functions
Python includes following functions that perform mathematical
calculations.
Function Returns ( description )

abs(x) The absolute value of x: the (positive) distance


between x and zero.

ceil(x) The ceiling of x: the smallest integer not less than x

cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y

exp(x) The exponential of x: ex


fabs(x) The absolute value of x.

floor(x) The floor of x: the largest integer not greater than x

log(x) The natural logarithm of x, for x> 0

log10(x) The base-10 logarithm of x for x> 0 .

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

modf(x) The fractional and integer parts of x in a two-item


tuple. Both parts have the same sign as x. The
integer part is returned as a float.

pow(x, y) The value of x**y.

round(x [,n]) x rounded to n digits from the decimal point.


Python rounds away from zero as a tie-breaker:
round(0.5) is 1.0 and round(-0.5) is -1.0.

sqrt(x) The square root of x for x > 0


Random Number Functions
Random numbers are used for games, simulations, testing, security, and
privacy applications. Python includes following functions that are
commonly used.
Function Description

choice(seq) A random item from a list,


tuple, or string.

randrange ([start,] stop [,step]) A randomly selected element


from range(start, stop, step)

random() A random float r, such that 0 is


less than or equal to r and r is
less than 1

seed([x]) Sets the integer starting value


used in generating random
numbers. Call this function
before calling any other
random module function.
Returns None.

shuffle(lst) Randomizes the items of a list


in place. Returns None.

uniform(x, y) A random float r, such that x is


less than or equal to r and r is
less than y
Trigonometric Functions
Python includes following functions that perform trigonometric
calculations.
Function Description

acos(x) Return the arc cosine of x, in radians.

asin(x) Return the arc sine of x, in radians.

atan(x) Return the arc tangent of x, in radians.

atan2(y, x) Return atan(y / x), in radians.

cos(x) Return the cosine of x radians.

hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).

sin(x) Return the sine of x radians.

tan(x) Return the tangent of x radians.

degrees(x) Converts angle x from radians to degrees.

radians(x) Converts angle x from degrees to radians.


Mathematical Constants
The module also defines two mathematical constants −
Constants Description

pi The mathematical constant pi.


e The mathematical constant e.

Python Files I/O


Printing to the Screen
The simplest way to produce output is using the print statement where you
can pass zero or more expressions separated by commas. This function
converts the expressions you pass into a string and writes the result to
standard output as follows −

#!/usr/bin/python

print "Python is really a great language,", "isn't it?"

This produces the following result on your standard screen −

Python is really a great language, isn't it?

Reading Keyboard Input


Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −

 raw_input

 input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input
and returns it as a string (removing the trailing newline).

#!/usr/bin/python

str = raw_input("Enter your input: ");


print "Received input is : ", str

This prompts you to enter any string and it would display same string on
the screen. When I typed "Hello Python!", its output is like this −

Enter your input: Hello Python


Received input is : Hello Python

The input Function


The input([prompt]) function is equivalent to raw_input, except that it
assumes the input is a valid Python expression and returns the evaluated
result to you.

#!/usr/bin/python

str = input("Enter your input: ");


print "Received input is : ", str

This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]


Recieved input is : [10, 20, 30, 40]

File
What Is a File?
Before we can go into how to work with files in Python, itʼs important to
understand what exactly a file is and how modern operating systems handle some
of their aspects.

At its core, a file is a contiguous set of bytes used to store data. This data is
organized in a specific format and can be anything as simple as a text file or as
complicated as a program executable. In the end, these byte files are then
translated into binary 1 and 0 for easier processing by the computer.

Files on most modern file systems are composed of three main parts:

1. Header: metadata about the contents of the file (file name, size, type, and so
on)
2. Data: contents of the file as written by the creator or editor
3. End of file (EOF): special character that indicates the end of the file
What this data represents depends on the format specification used, which is
typically represented by an extension. For example, a file that has an extension
of .gif most likely conforms to the Graphics Interchange Format specification.
There are hundreds, if not thousands, of file extensions out there. For this tutorial,
youʼll only deal with .txt or .csv file extensions.

File Paths
When you access a file on an operating system, a file path is required. The file path is a string
that represents the location of a file. It’s broken up into three major parts:

1. Folder Path: the file folder location on the file system where subsequent folders are separated
by a forward slash / (Unix) or backslash \ (Windows)
2. File Name: the actual name of the file
3. Extension: the end of the file path pre-pended with a period (.) used to indicate the file type
Hereʼs a quick example. Letʼs say you have a file located within a file structure
like this:


├── path/
| │
│ ├── to/
│ │ └── cats.gif
│ │
│ └── dog_breeds.txt
|
└── animals.csv
Let’s say you wanted to access the cats.gif file, and your current location was in the same
folder as path. In order to access the file, you need to go through the path folder and then
the to folder, finally arriving at the cats.gif file. The Folder Path is path/to/. The File Name
is cats. The File Extension is .gif. So the full path is path/to/cats.gif.

Now let’s say that your current location or current working directory (cwd) is in the to folder of
our example folder structure. Instead of referring to the cats.gif by the full path
of path/to/cats.gif, the file can be simply referenced by the file name and
extension cats.gif.

/

├── path/
| │
| ├── to/ ← Your current working directory (cwd) is here
| │ └── cats.gif ← Accessing this file
| │
| └── dog_breeds.txt
|
└── animals.csv
But what about dog_breeds.txt? How would you access that without using the full path? You
can use the special characters double-dot (..) to move one directory up. This means
that ../dog_breeds.txt will reference the dog_breeds.txt file from the directory of to:

/

├── path/ ← Referencing this parent folder
| │
| ├── to/ ← Current working directory (cwd)
| │ └── cats.gif
| │
| └── dog_breeds.txt ← Accessing this file
|
└── animals.csv
The double-dot (..) can be chained together to traverse multiple directories above the current
directory. For example, to access animals.csv from the to folder, you would
use ../../animals.csv.

Line Endings
One problem often encountered when working with file data is the representation of a new line
or line ending. The line ending has its roots from back in the Morse Code era, when a specific
pro-sign was used to communicate the end of a transmission or the end of a line.

Pug\r\n
Jack Russell Terrier\r\n
English Springer Spaniel\r\n
German Shepherd\r\n
Staffordshire Bull Terrier\r\n
Cavalier King Charles Spaniel\r\n
Golden Retriever\r\n
West Highland White Terrier\r\n
Boxer\r\n
Border Terrier\r\n

Opening and Closing Files


Python provides basic functions and methods necessary to manipulate files
by default. You can do most of the file manipulation using a file object.
The open Function

Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be
utilized to call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])

Here are parameter details:

 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 is given below in the table. This is optional parameter
and the default file access mode is read (r).

 buffering: If the buffering value is set to 0, no buffering takes place.


If the buffering value is 1, line buffering is performed while accessing
a file. If you specify the buffering value as an integer greater than 1,
then buffering action is performed with the indicated buffer size. If
negative, the buffer size is the system default(default behavior).
Here is a list of the different modes of opening a file −

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
placed at the beginning of the file.

rb+ Opens a file for both reading and writing in binary format.
The file pointer placed at the beginning of the file.

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.

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.

The file Object Attributes


Once a file is opened and you have one file object, you can get various
information related to that file.
Here is a list of all attributes related to file object:

Attribute Description

file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened.

file.name Returns name of the file.

file.softspace Returns false if space explicitly required with print, true


otherwise.

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

This produces the following result −

Name of the file: foo.txt


Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and
closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.
Syntax
fileObject.close();

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file


fo.close()

This produces the following result −

Name of the file: foo.txt


Reading and Writing Files
The file object provides a set of access methods to make our lives easier.
We would see how to use read() and write() methods to read and write
files.
The write() Method
The write() method writes any string to an open file. It is important to
note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of
the string −
Syntax
fileObject.write(string);

Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");

# Close opend file


fo.close()

The above method would create foo.txt file and would write given content
in that file and finally it would close that file. If you would open this file, it
would have following content.

Python is a great language.


Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note
that Python strings can have binary data. apart from text data.
Syntax
fileObject.read([count]);

Here, passed parameter is the number of bytes to be read from the opened
file. This method starts reading from the beginning of the file and
if count is missing, then it tries to read as much as possible, maybe until
the end of file.
Example
Let's take a file foo.txt, which we created above.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

This produces the following result −

Read String is : Python is

File Positions
The tell() method tells you the current position within the file; in other
words, the next read or write will occur at that many bytes from the
beginning of the file.
The seek(offset[, from]) method changes the current file position.
The offsetargument indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes
are to be moved.
If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position and
if it is set to 2 then the end of the file would be taken as the reference
position.
Example
Let us take a file foo.txt, which we created above.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str

# Check current position


position = fo.tell();
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()

This produces the following result −

Read String is : Python is


Current file position : 10
Again read String is : Python is

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any
related functions.
The rename() Method
The rename() method takes two arguments, the current filename and the
new filename.
Syntax
os.rename(current_file_name, new_file_name)

Example
Following is the example to rename an existing file test1.txt:

#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )

The remove() Method


You can use the remove() method to delete files by supplying the name of
the file to be deleted as the argument.
Syntax
os.remove(file_name)

Example
Following is the example to delete an existing file test2.txt −

#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")

Directories in Python
All files are contained within various directories, and Python has no
problem handling these too. The os module has several methods that help
you create, remove, and change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in
the current directory. You need to supply an argument to this method
which contains the name of the directory to be created.
Syntax
os.mkdir("newdir")

Example
Following is the example to create a directory test in the current directory

#!/usr/bin/python
import os

# Create a directory "test"


os.mkdir("test")

The chdir() Method


You can use the chdir() method to change the current directory. The
chdir() method takes an argument, which is the name of the directory that
you want to make the current directory.
Syntax
os.chdir("newdir")

Example
Following is the example to go into "/home/newdir" directory −

#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")

The getcwd() Method


The getcwd() method displays the current working directory.
Syntax
os.getcwd()

Example
Following is the example to give current directory −

#!/usr/bin/python
import os

# This would give location of the current directory


os.getcwd()

The rmdir() Method


The rmdir() method deletes the directory, which is passed as an argument
in the method.
Before removing a directory, all the contents in it should be removed.
Syntax:
os.rmdir('dirname')

Example
Following is the example to remove "/tmp/test" directory. It is required to
give fully qualified name of the directory, otherwise it would search for
that directory in the current directory.

#!/usr/bin/python
import os

# This would remove "/tmp/test" directory.


os.rmdir( "/tmp/test" )

File & Directory Related Methods


There are three important sources, which provide a wide range of utility
methods to handle and manipulate files & directories on Windows and
Unix operating systems. They are as follows −

 File Object Methods: The file object provides functions to manipulate


files.

 A file object is created using open function and here is a list of


functions which can be called on this object −

SN Methods with Description

1 file.close()
Close the file. A closed file cannot be read or written any more.
2 file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op
on some file-like objects.

3 file.fileno()
Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating
system.

4 file.isatty()
Returns True if the file is connected to a tty(-like) device, else
False.

5 file.next()
Returns the next line from the file each time it is being called.

6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF
before obtaining size bytes).

7 file.readline([size])
Reads one entire line from the file. A trailing newline character is
kept in the string.

8 file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the
lines. If the 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.
9 file.seek(offset[, whence])
Sets the file's current position

10 file.tell()
Returns the file's current position

11 file.truncate([size])
Truncates the file's size. If the optional size argument is present,
the file is truncated to (at most) that size.

12 file.write(str)
Writes a string to the file. There is no return value.

13 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.

 OS Object Methods: This provides methods to process files as well as


directories.

command line arguments

Errors and Exceptions

Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common
kind of complaint you get:
>>>

>>> while True print 'Hello world'


File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at
the earliest point in the line where the error was detected. The error is
caused by (or at least detected at) the token preceding the arrow: in the
example, the error is detected at the keyword print, since a colon (':') is
missing before it. File name and line number are printed so you know
where to look in case the input came from a script.

Python provides two very important features to handle any unexpected


error in your Python programs and to add debugging capabilities in them

 Exception Handling: Here is a list standard Exceptions available


in Python: Standard Exceptions.

 Assertions: This would be covered in Assertions in Python.


List of Standard Exceptions −

EXCEPTION NAME DESCRIPTION

Exception Base class for all exceptions

StopIteration Raised when the next() method


of an iterator does not point to
any object.

SystemExit Raised by the sys.exit() function.

StandardError Base class for all built-in


exceptions except StopIteration
and SystemExit.

ArithmeticError Base class for all errors that


occur for numeric calculation.

OverflowError Raised when a calculation


exceeds maximum limit for a
numeric type.

FloatingPointError Raised when a floating point


calculation fails.

ZeroDivisonError Raised when division or modulo


by zero takes place for all
numeric types.

AssertionError Raised in case of failure of the


Assert statement.

AttributeError Raised in case of failure of


attribute reference or
assignment.

EOFError Raised when there is no input


from either the raw_input() or
input() function and the end of
file is reached.

ImportError Raised when an import


statement fails.

KeyboardInterrupt Raised when the user interrupts


program execution, usually by
pressing Ctrl+c.
LookupError Base class for all lookup errors.

IndexError Raised when an index is not


found in a sequence.
KeyError
Raised when the specified key is
not found in the dictionary.

NameError Raised when an identifier is not


found in the local or global
namespace.

UnboundLocalError Raised when trying to access a


local variable in a function or
EnvironmentError method but no value has been
assigned to it.
Base class for all exceptions that
occur outside the Python
environment.

IOError Raised when an input/ output


operation fails, such as the print
IOError statement or the open()
function when trying to open a
file that does not exist.
Raised for operating system-
related errors.

SyntaxError Raised when there is an error in


Python syntax.
IndentationError
Raised when indentation is not
specified properly.
SystemError Raised when the interpreter
finds an internal problem, but
when this error is encountered
the Python interpreter does not
exit.

SystemExit Raised when Python interpreter


is quit by using the sys.exit()
function. If not handled in the
code, causes the interpreter to
exit.

Raised when Python interpreter is Raised when an operation or


quit by using the sys.exit() function. function is attempted that is
If not handled in the code, causes invalid for the specified data
the interpreter to exit. type.

ValueError Raised when the built-in


function for a data type has the
valid type of arguments, but the
arguments have invalid values
specified.

RuntimeError Raised when a generated error


does not fall into any category.

NotImplementedError Raised when an abstract method


that needs to be implemented in
an inherited class is not actually
implemented.

Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you
are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-
if statement (or to be more accurate, a raise-if-not statement). An
expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for
valid input, and after a function call to check for valid output.
The assert Statement
When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true. If the expression is
false, Python raises anAssertionError exception.
The syntax for assert is −

assert Expression[, Arguments]

If the assertion fails, Python uses ArgumentExpression as the argument for


the AssertionError. AssertionError exceptions can be caught and handled
like any other exception using the try-except statement, but if not handled,
they will terminate the program and produce a traceback.
Example
Here is a function that converts a temperature from degrees Kelvin to
degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the
function bails out if it sees a negative temperature −

#!/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)

When the above code is executed, it produces the following result −

32.0
451
Traceback (most recent call last):
File "test.py", line 9, in
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.
Syntax
Here is simple syntax of try....except...else blocks −

try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −


 A single try statement can have multiple except statements. This is
useful when the try block contains statements that may throw
different types of exceptions.

 You can also provide a generic except clause, which handles any
exception.

 After the except clause(s), you can include an else-clause. The code in
the else-block executes if the code in the try: block does not raise an
exception.

 The else-block is a good place for code that does not need the try:
block's protection.
Example
This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all −

#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()

This produces the following result −

Written content in the file successfully


Example
This example tries to open a file where you do not have write permission,
so it raises an exception −
#!/usr/bin/python

try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"

This produces the following result −

Error: can't find file or read data


The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as
follows −

try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good
programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may
occur.
The except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions
as follows −

try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.

The try-finally Clause


You can use a finally: block along with a try: block. The finally block is a
place to put any code that must execute, whether the try-block raised an
exception or not. The syntax of the try-finally statement is this −

try:
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
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"

If you do not have permission to open the file in writing mode, then this
will produce the following result:

Error: can't find file or read data

Same example can be written more cleanly as follows −

#!/usr/bin/python

try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"

When an exception is thrown in the try block, the execution immediately


passes to the finally block. After all the statements in the finally block are
executed, the exception is raised again and is handled in
the except statements if present in the next higher layer of the try-
except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by
exception. You capture an exception's argument by supplying a variable in
the except clause as follows −

try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...

If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are
trapping multiple exceptions, you can have a variable follow the tuple of
the exception.
This variable receives the value of the exception mostly containing the
cause of the exception. The variable can receive a single value or multiple
values in the form of a tuple. This tuple usually contains the error string,
the error number, and an error location.
Example
Following is an example for a single exception −

#!/usr/bin/python

# Define a function here.


def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument

# Call above function here.


temp_convert("xyz");
This produces the following result −

The argument does not contain numbers


invalid literal for int() with base 10: 'xyz'
Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The
general syntax for the raise statement is as follows.
Syntax
raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (for example, NameError)


andargument is a value for the exception argument. The argument is
optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in
practice), and if present, is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions
that the Python core raises are classes, with an argument that is an
instance of the class. Defining new exceptions is quite easy and can be
done as follows −

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

Note: In order to catch an exception, an "except" clause must refer to the


same exception thrown either class object or simple string. For example, to
capture above exception, we must write the except clause as follows −

try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...

User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that
is subclassed from RuntimeError. This is useful when you need to display
more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the
except block. The variable e is used to create an instance of the
class Networkerror.

class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg

So once you defined above class, you can raise the exception as follows −

try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args

Python Functions
A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your
application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(),
etc. but you can also create your own functions. These functions are
called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are
simple rules to define a function in Python.

 Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).

 Any input parameters or arguments should be placed within these


parentheses. You can also define parameters inside these
parentheses.

 The first statement of a function can be an optional statement - the


documentation string of the function or docstring.

 The code block within every function starts with a colon (:) and is
indented.

 The statement return [expression] exits a function, optionally passing


back an expression to the caller. A return statement with no
arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform


them in the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on
standard screen.

def printme( str ):


"This prints a passed string into this function"
print str
return

Calling a Function
Defining a function only gives it a name, specifies the parameters that are
to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by
calling it from another function or directly from the Python prompt.
Following is the example to call printme() function −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result −

I'm first call to user defined function!


Again second call to the same function

Pass by reference vs value


All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a
function, the change also reflects back in the calling function. For example

#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending


values in the same object. So, this would produce the following result −

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference


and the reference is being overwritten inside the called function.

#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist


within the function does not affect mylist. The function accomplishes
nothing and finally this would produce the following result:

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

Function Arguments
You can call a function by using the following types of formal arguments:

 Required arguments

 Keyword arguments

 Default arguments

 Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result:

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters. You can also make keyword calls to
the printme() function in the following ways −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −

My string
The following example gives more clear picture. Note that the order of
parameters does not matter.

#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

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

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-
lengtharguments and are not named in the function definition, unlike
required and default arguments.
Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of
all nonkeyword variable arguments. This tuple remains empty if no
additional arguments are specified during the function call. Following is a
simple example −

#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −

Output is:
10
Output is:
70
60
50

Functional programming
The Anonymous Functions
These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.

 Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands
or multiple expressions.
 An anonymous function cannot be a direct call to print because
lambda requires an expression

 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the
global namespace.

 Although it appears that lambda's are a one-line version of a


function, they are not equivalent to inline statements in C or C++,
whose purpose is by passing function stack allocation during
invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is
as follows −

lambda [arg1 [,arg2,.....argn]]:expression

Following is the example to show how lambda form of function works −

#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −

Value of total : 30
Value of total : 40

The return Statement


The statement return [expression] exits a function, optionally passing back
an expression to the caller. A return statement with no arguments is the
same as return None.
All the above examples are not returning any value. You can return a value
from a function as follows −

#!/usr/bin/python

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −

Inside the function : 30


Outside the function : 30

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
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
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

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −

Inside the function local total : 30


Outside the function global total : 0

Python Modules
Function is a block of code which execute some logic. Module is a bundle
of functions. Modules contain n function inside.
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
namedaname.py. Here's an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return

The import Statement


You can use any Python source file as a module by executing an import
statement in some other Python source file. The import has the following
syntax:

import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the


module if the module is present in the search path. A search path is a list of
directories that the interpreter searches before importing a module. For
example, to import the module hello.py, you need to put the following
command at the top of the script −

#!/usr/bin/python

# Import module support


import support

# Now you can call defined function that module as follows


support.print_func("Zara")

When the above code is executed, it produces the following result −


Hello : Zara

A module is loaded only once, regardless of the number of times it is


imported. This prevents the module execution from happening over and
over again if multiple imports occur.
The from...import Statement
Python's from statement lets you import specific attributes from a module
into the current namespace. The from...import has the following syntax −

from modname import name1[, name2[, ... nameN]]

For example, to import the function fibonacci from the module fib, use the
following statement −

from fib import fibonacci

This statement does not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into
the global symbol table of the importing module.
The from...import * Statement:
It is also possible to import all names from a module into the current
namespace by using the following import statement −

from modname import *

This provides an easy way to import all the items from a module into the
current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the
module in the following sequences −

 The current directory.

 If the module isn't found, Python then searches each directory in the
shell variable PYTHONPATH.

 If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as
the sys.pathvariable. The sys.path variable contains the current directory,
PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable:
The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.
Here is a typical PYTHONPATH from a Windows system:

set PYTHONPATH=c:\python20\lib;

And here is a typical PYTHONPATH from a UNIX system:

set PYTHONPATH=/usr/local/lib/python

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).
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.
Python makes educated guesses on whether variables are local or global. It
assumes that any variable assigned a value in a function is local.
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 function Money, we assign Money a value, therefore Python
assumes Money as a local variable. However, we accessed the value of the
local variable Moneybefore setting it, so an UnboundLocalError is the
result. Uncommenting the global statement fixes the problem.

#!/usr/bin/python

Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1

print Money
AddMoney()
print Money

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the
names defined by a module.
The list contains the names of all the modules, variables and functions that
are defined in a module. Following is a simple example −

#!/usr/bin/python

# Import built-in module math


import math

content = dir(math)

print content

When the above code is executed, it produces the following result −


['__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.
The globals() and locals() Functions −
The globals() and locals() functions can be used to return the names in the
global and local namespaces depending on the location from where they
are called.
If locals() is called from within a function, it will return all the names that
can be accessed locally from that function.
If globals() is called from within a function, it will return all the names that
can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can
be extracted using the keys() function.
The reload() Function
When the module is imported into a script, the code in the top-level
portion of a module is executed only once.
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"

Similar way, we have another two files having different functions with the
same name as above −

 Phone/Isdn.py file having function Isdn()

 Phone/G3.py file having function G3()


Now, create one more file __init__.py in Phone directory −

 Phone/__init__.py
To make all of your functions available when you've imported Phone, you
need to put explicit import statements in __init__.py as follows −

from Pots import Pots


from Isdn import Isdn
from G3 import G3

After you add these lines to __init__.py, you have all of these classes
available when you import the Phone package.

#!/usr/bin/python

# Now import your Phone Package.


import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()

When the above code is executed, it produces the following result −

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone

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.

Python has been an object-oriented language since it existed. Because of


this, creating and using classes and objects are downright easy. This
chapter helps you become an expert in using Python's object-oriented
programming support.

If you do not have any previous experience with object-oriented (OO)


programming, you may want to consult an introductory course on it or at
least a tutorial of some sort so that you have a grasp of the basic concepts.

However, here is small introduction of Object-Oriented Programming (OOP)


to bring you at speed −

Python Object Oriented

Overview of OOP Terminology


 Class: A user-defined prototype for an object that defines a set of attributes
that characterize any object of the class. The attributes are data members
(class variables and instance variables) and methods, accessed via dot notation.

 Class variable: A variable that is shared by all instances of a class. Class


variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables are.

 Data member: A class variable or instance variable that holds data associated
with a class and its objects.

 Function overloading: The assignment of more than one behavior to a


particular function. The operation performed varies by the types of objects or
arguments involved.

 Instance variable: A variable that is defined inside a method and belongs only
to the current instance of a class.

 Inheritance: The transfer of the characteristics of a class to other classes that


are derived from it.

 Instance: An individual object of a certain class. An object obj that belongs to a


class Circle, for example, is an instance of the class Circle.

 Instantiation: The creation of an instance of a class.

 Method : A special kind of function that is defined in a class definition.

 Object: A unique instance of a data structure that's defined by its class. An


object comprises both data members (class variables and instance variables)
and methods.

 Operator overloading: The assignment of more than one function to a


particular operator.

Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:

'Optional class documentation string'

class_suite

 The class has a documentation string, which can be accessed


viaClassName.__doc__.

 The class_suite consists of all the component statements defining class


members, data attributes and functions.

Example
Following is the example of a simple Python class −

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

 The variable empCount is a class variable whose value is shared among all
instances of a this class. This can be accessed asEmployee.empCount from
inside the class or outside the class.

 The first method __init__() is a special method, which is called class constructor
or initialization method that Python calls when you create a new instance of this
class.
 You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to the
list for you; you do not need to include it when you call the methods.

Creating Instance Objects


To create instances of a class, you call the class using class name and pass
in whatever arguments its __init__ method accepts.

"This would create first object of Employee class"

emp1 = Employee("Zara", 2000)

"This would create second object of Employee class"

emp2 = Employee("Manni", 5000)

Accessing Attributes
You access the object's attributes using the dot operator with object. Class
variable would be accessed using class name as follows −

emp1.displayEmployee()

emp2.displayEmployee()

print "Total Employee %d" % Employee.empCount

Now, putting all the concepts together −

#!/usr/bin/python

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"

emp1 = Employee("Zara", 2000)

"This would create second object of Employee class"

emp2 = Employee("Manni", 5000)

emp1.displayEmployee()

emp2.displayEmployee()

print "Total Employee %d" % Employee.empCount

When the above code is executed, it produces the following result −

Name : Zara ,Salary: 2000

Name : Manni ,Salary: 5000

Total Employee 2

You can add, remove, or modify attributes of classes and objects at any
time −

emp1.age = 7 # Add an 'age' attribute.

emp1.age = 8 # Modify 'age' attribute.

del emp1.age # Delete 'age' attribute.

Instead of using the normal statements to access attributes, you can use
the following functions −

 The getattr(obj, name[, default]) : to access the attribute of object.

 The hasattr(obj,name) : to check if an attribute exists or not.

 The setattr(obj,name,value) : to set an attribute. If attribute does not exist,


then it would be created.

 The delattr(obj, name) : to delete an attribute.


hasattr(emp1, 'age') # Returns true if 'age' attribute exists

getattr(emp1, 'age') # Returns value of 'age' attribute

setattr(emp1, 'age', 8) # Set attribute 'age' at 8

delattr(empl, 'age') # Delete attribute 'age'

Built-In Class Attributes


Every Python class keeps following built-in attributes and they can be
accessed using dot operator like any other attribute −

 __dict__: Dictionary containing the class's namespace.

 __doc__: Class documentation string or none, if undefined.

 __name__: Class name.

 __module__: Module name in which the class is defined. This attribute is


"__main__" in interactive mode.

 __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 __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount


def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__

print "Employee.__name__:", Employee.__name__

print "Employee.__module__:", Employee.__module__

print "Employee.__bases__:", Employee.__bases__

print "Employee.__dict__:", Employee.__dict__

When the above code is executed, it produces the following result −

Employee.__doc__: Common base class for all employees


Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

Destroying Objects (Garbage Collection)


Python deletes unneeded objects (built-in types or class instances)
automatically to free the memory space. The process by which Python
periodically reclaims blocks of memory that no longer are in use is termed
Garbage Collection.

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.

An object's reference count increases when it is assigned a new name or


placed in a container (list, tuple, or dictionary). The object's reference count
decreases when it's deleted with del, its reference is reassigned, or its
reference goes out of scope. When an object's reference count reaches
zero, Python collects it automatically.
a = 40 # Create object <40>

b = a # Increase ref. count of <40>

c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>

b = 100 # Decrease ref. count of <40>

c[0] = -1 # Decrease ref. count of <40>

You normally will not notice when the garbage collector destroys an
orphaned instance and reclaims its space. But a class can implement the
special method__del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up
any non memory resources used by an instance.

Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −

#!/usr/bin/python

class Point:

def __init( self, x=0, y=0):

self.x = x

self.y = y

def __del__(self):

class_name = self.__class__.__name__

print class_name, "destroyed"

pt1 = Point()

pt2 = pt1

pt3 = pt1

print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts

del pt1

del pt2
del pt3

When the above code is executed, it produces following result −

3083401324 3083401324 3083401324

Point destroyed

Note: Ideally, you should define your classes in separate file, then you
should import them in your main program file using import statement.

Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a
preexisting class by listing the parent class in parentheses after the new
class name.

The child class inherits the attributes of its parent class, and you can use
those attributes as if they were defined in the child class. A child class can
also override data members and methods from the parent.

Syntax
Derived classes are declared much like their parent class; however, a list of
base classes to inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):

'Optional class documentation string'

class_suite

Example
#!/usr/bin/python

class Parent: # define parent class

parentAttr = 100

def __init__(self):

print "Calling parent constructor"

def parentMethod(self):

print 'Calling parent method'


def setAttr(self, attr):

Parent.parentAttr = attr

def getAttr(self):

print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class

def __init__(self):

print "Calling child constructor"

def childMethod(self):

print 'Calling child method'

c = Child() # instance of child

c.childMethod() # child calls its method

c.parentMethod() # calls parent's method

c.setAttr(200) # again call parent's method

c.getAttr() # again call parent's method

When the above code is executed, it produces the following result −

Calling child constructor

Calling child method

Calling parent method

Parent attribute : 200

Similar way, you can drive a class from multiple parent classes as follows −

class A: # define your class A

.....

class B: # define your calss B

.....
class C(A, B): # subclass of A and B

.....

You can use issubclass() or isinstance() functions to check a relationships of


two classes and instances.

 The issubclass(sub, sup) boolean function returns true if the given


subclass sub is indeed a subclass of the superclass sup.

 The isinstance(obj, Class) boolean function returns true if obj is an instance of


class Class or is an instance of a subclass of Class

Overriding Methods
You can always override your parent class methods. One reason for
overriding parent's methods is because you may want special or different
functionality in your subclass.

Example
#!/usr/bin/python

class Parent: # define parent class

def myMethod(self):

print 'Calling parent method'

class Child(Parent): # define child class

def myMethod(self):

print 'Calling child method'

c = Child() # instance of child

c.myMethod() # child calls overridden method

When the above code is executed, it produces the following result −

Calling child method

Base Overloading Methods


Following table lists some generic functionality that you can override in your
own classes −

SN Method, Description & Sample Call

1 __init__ ( self [,args...] )


Constructor (with any optional arguments)
Sample Call : obj = className(args)

2 __del__( self )
Destructor, deletes an object
Sample Call : del obj

3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)

4 __str__( self )
Printable string representation
Sample Call : str(obj)

5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Overloading Operators
Suppose you have created a Vector class to represent two-dimensional
vectors, what happens when you use the plus operator to add them? Most
likely Python will yell at you.

You could, however, define the __add__ method in your class to perform
vector addition and then the plus operator would behave as per expectation

Example
#!/usr/bin/python

class Vector:

def __init__(self, a, b):

self.a = a

self.b = b

def __str__(self):

return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):

return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)

v2 = Vector(5,-2)

print v1 + v2

When the above code is executed, it produces the following result −

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

When the above code is executed, it produces the following result −

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

When the above code is executed, it produces the following result −

1
2
2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy