PYTHON TRAINING
Agenda
 Dictionary
 Conditional Statements
 Loops & Iteration
 List & Dictionary Comprehension
 FUNCTIONS
 MODULES & PACKAGES
 INPUT & OUTPUT
 Error Handling
 OOPs
 Introduction
 Python Features
 Python Structure
 Python Basics
 Comments
 Variables
 Basic programming
 Basic operators
 Data Types
 Numbers
 Strings
 Lists
 Tuple
Introduction
 Python is Interpreted: Code is processed at runtime by the interpreter and
you do not need to compile your program before executing it.
 Python is Interactive: Coding can be done 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 employs
the concept of modularization.
Introduction Contd….
 Python is Beginner's Language: Python is a great language for the
beginner programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
Python features
no compiling or linking rapid development cycle
no type declarations simpler, shorter, more flexible
automatic memory management garbage collection
high-level data types and
operations
fast development
object-oriented programming code structuring and reuse, C++
embedding and extending in C mixed language systems
classes, modules, exceptions "programming-in-the-large"
support
dynamic loading of C modules simplified extensions, smaller
binaries
dynamic reloading of C modules programs can be modified without
stopping
Python features
universal "first-class" object model fewer restrictions and rules
run-time program construction handles unforeseen needs, end-
user coding
interactive, dynamic nature incremental development and
testing
access to interpreter information metaprogramming, introspective
objects
wide portability cross-platform programming
without ports
compilation to portable byte-code execution speed, protecting source
code
built-in interfaces to external
services
system tools, GUIs, persistence,
databases, etc.
Python Structure
 modules: Python source files or C extensions
 import, top-level via from, reload
 statements
 control flow
 create objects
 indentation matters – instead of {}
 objects
 everything is an object
 automatically reclaimed when no longer needed
Python Basics
 /usr/local/bin/python
 #! /usr/bin/env python
 interactive use
Python 1.6 (#1, Sep 24 2000, 20:40:45) [GCC 2.95.1 19990816 (release)] on sunos5
Copyright (c) 1995-2000 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>>
 python –c command [arg] ...
 python –i script
 read script first, then interactive
Python Basics Contd….
 An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9)
 Naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
 Starting an identifier with a single leading underscore indicates that
the identifier is private.
 Starting an identifier with two leading underscores indicates a strongly
private identifier.
 If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.
 Lines and Indentation
 All the continuous lines indented with same number of spaces would
form a block.
Python Basics Contd….
 Reserved Words
And exec Not
Assert finally or
Break for pass
Class from print
Continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Comments
 A hash sign (#) that is not inside a string literal begins a comment.
 All characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print "Hello, Python!"; # second comment
This produces the following result −
Hello, Python!
Variables
 Assigning Values to Variables
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
 Output
100
1000.0
John
 Multiple Assignments
a, b, c = 1, 2, "john"
Basic programming
a,b = 0, 1
# non-zero = true
while b < 10:
# formatted output, without n
print b,
# multiple assignment
a,b = b, a+b
Basic operators
Python language supports the following types of operators.
 Arithmetic Operators
+, -, *, /, %, **, //
 Comparison (Relational) Operators
==, !=, <>, >, <, >=, <=
 Assignment Operators
=, +=, -=, *=, /=, %=, **=, //=
 Logical Operators
and, or, Not
 Bitwise Operators
& (Binary AND), | (Binary OR), ^ (Binary XOR), ~ (Binary Ones Complement), << (Binary Left Shift), >> (Binary Right
Shift)
 Membership Operators
is, is not
 Identity Operators
is, is not
Data Types
Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
Numbers
 int (signed integers)
 signed integers 10,-723
 long (long integers, they can also be represented in octal and hexadecimal)
 (octal+hex) 0122L
 float (floating point real values)
 1.4,9.23
 complex (complex numbers)
 3e+26j
Numbers Contd….
 In Python, Numbers are immutable
 Assigning Numbers
var1 = 1
var2 = 10
 Deleting one or more variables
del var1[,var2[,var3[....,varN]]]]
del var1
del var1, var2
Strings
 In Python, Strings are immutable
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
var1 = 'Hello World!'
var2 = "Python Programming“
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
 Result
var1[0]: H
var2[1:5]: ytho
 Operations on Strings (slicing)
#!/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
 Result
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Strings Contd….
 String Updation
 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
#!/usr/bin/python
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python‘
 Result:
Updated String :- Hello Python
Strings Contd….
Escape Characters
 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.
e.g.
t, s, e, n, b, v
Strings Contd….
String Special Operators
 Assume string variable a holds 'Hello' and variable b holds 'Python', then
Operator Example
+ a + b will give HelloPython
* a*2 will give -HelloHello
[] a[1] will give e
[ : ] a[1:4] will give ell
in H in a will give 1
not in M not in a will give 1
r/R print r'n' prints n and print R'n'prints n
% See at next section
Strings Contd….
 String Formatting Operators
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
 Result:
My name is Zara and weight is 21 kg!
Strings Contd….
 Count() – returns the count of a substring in a string
 Len() – returns the length of string
 Find() – returns index if str is found else -1
 Strip() – removes spaces
-rstrip
-lstrip
 Capitalize() -Capitalizes first letter of string
 Upper() – converts to upper case
 Lower() - converts to lower case
Strings Contd….
 Don’t forget to try what these buddies will do in python shell:
Replace()
Istitle()
Endswith()
Split()
Translate()
Isspace()
Isdecimal()
Lists
 The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is
zero, the second index is one, and so forth.
 Python has six built-in types of sequences
 operations on sequences:- indexing, slicing, adding, multiplying, and
checking for membership
Lists Contd….
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
list3 = ["a", "b", "c", "d"];
 Accessing Values:
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
 Result:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Lists Contd….
 Updating Lists
#!/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];
 Result:
Value available at index 2 :
1997
New value available at index 2 :
2001
Lists Contd….
 Delete List Elements
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
 Result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Lists Contd….
 Basic List Operations
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!', 'Hi!'] Repetition
3 in [1, 2, 3] TRUE Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration
Lists Contd….
 Slicing
L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam'
Negative: count from the
right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Lists Contd….
 Built-in List Functions
SN Function with Description
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
Lists Contd….
 Built-in List Methods
SN Function with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
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
Tuple
 A tuple is a sequence of immutable Python objects
 Created with open parenthesis ()
• Example : tuple1=(1,2,3)
• Empty Tuple : tup()
• Tuple with single value : tuple1(10,)
Accessing Tuple elements:
 Can be accessed using index
 Tuple1= (1,2,3,4,5)
 Print Tuple1[0] will print 1
 Print tuple1[1:3] will print 2,3
 Print tuple1[0:] will print 1,2,3,4,5
Tuple Contd….
 Updating Tuples
#!/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;
 Result
(12, 34.56, 'abc', 'xyz')
Tuple Contd….
 Deleting Tuples
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : "
print tup;
 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):
Tuples Contd….
 Basic Tuple Operations
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!', 'Hi!‘) Repetition
3 in (1, 2, 3) TRUE Membership
for x in (1, 2, 3): print x, 1 2 3 Iteration
Tuple Contd….
 Slicing
L = ('spam', 'Spam', 'SPAM!‘)
Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam'
Negative: count from the
right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Tuple Contd….
 Built-in Tuple Functions
SN Function with Description
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a tuple into list.
Dictionary
 Dictionaries consist of pairs of keys and their corresponding values.
 Created using curly braces {}
dict1={'name':'sathya','emp ':123,'location':'Chennai'}
 No indexing, as the values are accessed through Keys not index.
 No duplicate key is allowed. When duplicate keys encountered
during assignment, the last assignment wins..
 Keys must be immutable. Which means you can use strings,
numbers or tuples as dictionary keys
 The values of a dictionary can be of any type, may not be unique.
Dictionary Contd…
• Accessing Values in Dictionary:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
• Result:
dict['Name']: Zara
dict['Age']: 7
Dictionary Contd….
• Updating Dictionary:
#!/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'];
• Result:
dict['Name']: Zara
dict['Age']: 7
Dictionary Contd….
• Deleting Dictionary Elements:
#!/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‘
• Result:
dict['Age']:
Traceback (most recent call last): File "test.py", line 8, in <module> print
"dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Dictionary Contd….
 Built-in Dictionary Functions
SNFunction 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.
Dictionary Contd….
 Built-in 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
Conditional Statements
Conditional Statements
Contd…. Decision Making
 Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome.
 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.
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).
Conditional Statements
Contd…. Decision Making Structure
Conditional Statements
Contd…. Python IF Statement
 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.
Conditional Statements
Contd…. Python IF Statement
Conditional Statements
Contd…. Python IF...ELSE Statements
 Syntax
if expression:
statement(s)
else:
statement(s)
 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 .
Conditional Statements
Contd…. Python IF...ELSE Statements
Conditional Statements
Contd…. Python 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.
 unlike else, for which there can be at most one statement, there can be an
arbitrary number of elif statements following an if.
 Syntaxif expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Conditional Statements
Contd…. Python nested IF statements
 To check for another condition after a condition resolves to true.
 Syntax
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
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.
 Ex:
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye! Let’s close the session "
Conditional Statements
Contd….
Loops and Iteration
 range() & xrange()
 range() is a function which create a lists containing arithmetic progressions. It
is most often used in for loops. The arguments must be plain integers. If the
step argument is omitted, it defaults to 1. If the start argument is omitted, it
defaults to 0.
 Parameters it takes: range(start , stop , step)
Loops and Iteration contd….
 While loop
 A while loop statement in Python programming language repeatedly
a target statement as long as a given condition is true.
Loops and Iteration contd….
 Syntax:
while expression:
statement(s)
Loops and Iteration contd….
 While loop
 Ex:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
Loops and Iteration contd….
An Infinite
Loop
n = 5
while n > 0 :
print ‘infinte loop’
print ‘Please stop me'
print ‘I am done’
n > 0 ?
No
print ‘I am done'
Yes
n = 5
print ‘infinite loop'
print ‘Please stop me'
Loops and Iteration contd….
Another Loop
n = 0
while n > 0 :
print ‘I am inside the loop’
print ‘I am out side the loop'
n > 0 ?
No
print ' I am out side the loop '
Yes
n = 0
print ' I am inside the
loop '
What does this loop do?
Loops and Iteration contd….
 Indefinite Loops
 While loops are called "indefinite loops" because they keep going until a
logical condition becomes False
 The loops we have seen so far are pretty easy to examine to see if they will
terminate or if they will be "infinite loops"
 Sometimes it is a little harder to be sure if a loop will terminate
Loops and Iteration contd….
 Definite Loops
 We can write a loop to run the loop once for each of the items in a set using
the Python for construct
 These loops are called "definite loops" because they execute an exact number
of times
 We say that "definite loops iterate through the members of a set"
Loops and Iteration contd….
• A Simple Definite
Loop
for i in [5, 4, 3, 2, 1] :
print i
5
4
3
2
1
Loops and Iteration contd….
• A Definite Loop with
Strings
friends = [‘Mahesh', ‘kiran', ‘Arun']
for friend in friends :
print 'Happy New Year:', friend
print 'Done!'
Happy New Year: Mahesh
Happy New Year: Kiran
Happy New Year: Arun
Done!
Loops and Iteration contd….
 Looking at In...
 The iteration variable
“iterates” though
sequence (ordered
set)
 The block (body) of
code is executed
once for each value
in the sequence
 The iteration variable
moves through all of
the values in the
sequence
for i in [5, 4, 3, 2, 1] :
print i
Iteration variable
Five-element sequence
Loops and Iteration contd….
 Loop Control Statements
 Loop control statements change execution from its normal sequence
 Python supports the following control statements
Break, continue, pass
Loops and Iteration contd….
 Breaking Out of a Loop
 The break statement ends the current loop and jumps to the
statement immediately following the loop
for letter in 'Python':
if letter == 'h':
break
print 'Current Letter :', letter
Loops and Iteration contd….
 Finishing an Iteration with continue
 The continue statement ends the current iteration and jumps to
top of the loop and starts the next iteration
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter
Loops and Iteration contd….
 Pass statement
 The pass statement in Python is used when a statement is required
but you do not want any command or code to execute. It is a null operation.
Loops and Iteration contd….
List & Dictionary Comprehension
List Comprehensions
 List comprehensions provide a concise way to create lists.
 It consists of brackets containing an expression followed by a for clause,
then zero or more for or if clauses.
 The result will be a new list resulting from evaluating the expression in the
context of the for and if clauses which follow it.
 The list comprehension always returns a result list.
List Comprehensions contd….
 Syntax
[ expression for item in list if conditional ]
 This is equivalent to:
for item in list:
if conditional:
expression
 Example
squares = [x**2 for x in range(10)]
print squares
 Result:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionary Comprehensions
 Dictionary comprehension is an elegant and
concise way to create new dictionary from an
iterable in Python.
 Dictionary comprehension consists of an
expression pair (key: value) followed by for
statement inside curly braces {}.
 A dictionary comprehension can optionally
contain more for or if statements.
Dictionary
Comprehensions
contd….
 Example:
squares = {x: x*x for x in range(6)}
print squares
 Result:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
 This is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print squares
FUNCTIONS
What is a Function ?
A function is a block of organized, reusable code that is used to perform a single,
related action
 Example of Function:
 Real World Example:
 Sending group messages
 Application Related Example:
 Working with excel
Syntax for defining a function
Function without parameter and without return type
def function_name():
declarations,operations
Function with parameter and without return type
def function_name(parameter):
declarations, operations
Function with parameter and with return type
def function_name(parameter):
declarations, operations
return [expression]
Function with unknown
number of arguments
 Eg: def fun(args):
 Print args
fun(2,3,5,6,……)
 Syntax :
def fun(*args):
for x in args:
print x
Global and local variable
 global variable_declaration
def function():
global variable_name
calculations based on global variable
def function():
local variable declaration
calculations based on local variable
Named Arguments
 When a function is called, parameters can be explicitly assigned a value by name.
These are often used to implement default values
 Eg 1: def foo(val1, val2, val3, calcSum=True):
# Calculate the sum
if calcSum:
return val1 + val2 + val3
# Calculate the average instead
else:
return (val1 + val2 + val3) / 3
foo(1,2,3,calcSum=True)
 Eg 2: def foo(val, arr=[]):
arr.append(val)
return arr
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 −# 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" );
**KWARGS (Keyword arguments)
 The reason why we specify ** because we are going to pass a
variable along with its value to the function
 Eg:
def print_table(**kwargs):
for key, value in kwargs.items():
print(key, value)
print_table(a = 5, b = 6, c = 7)
Lambda function
 Define one-line mini-functions
 No parentheses around the argument list, No return keyword
 In case if you want to use the value of a lambda function assign it to a variable and
then use it
Syntax:
variable=lambda argument: expression
 Eg 1:with one argument
g=lambda y:(y**2)
g(2)
 Eg 2: with many arguments
g=lambda *y:[(x**2) for x in y]
g(2,3,4)
Stack in Python
A stack (sometimes called a “push-down stack”) is an ordered collection of items where the addition of
new items and the removal of existing items always takes place at the same end. This end is commonly
referred to as the “top.” The end opposite the top is known as the “base.”
The stack is also referred as LIFO, last-in first-out. It provides an ordering based on length of time in
the collection. Newer items are near the top, while older items are near the base. Stack has some
methods to insert, remove …. Elements.
push(item) adds a new item to the top of the stack. It needs the item and returns nothing.
pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is
modified.
peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is
not modified.
isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value.
size() returns the number of items on the stack. It needs no parameters and returns an integer.
Implementing a Stack in Python
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
Queue
A queue is an ordered collection of items where the addition of new items happens at one
end, called the “rear,” and the removal of existing items occurs at the other end, commonly
called the “front.” As an element enters the queue it starts at the rear and makes its way
toward the front, waiting until that time when it is the next element to be removed.
Also it is known as FIFO, first-in first-out., as well as “first-come first-served.”
It has some methods to insert, delete …. Elements.
enqueue(item) adds a new item to the rear of the queue. It needs the item and returns
nothing.
dequeue() removes the front item from the queue. It needs no parameters and returns the
item. The queue is modified.
isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a
boolean value.
size() returns the number of items in the queue. It needs no parameters and returns an
integer
Implementing a Queue in Python
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
 MODULES & PACKAGES
Modules
A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier to
Understand and use.
A module is a Python object with arbitrarily named attributes
that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can
define functions, classes and variables. A module can also include
runnable code.
Example
The Python code for a module named aname normally resides in a file
named aname.py. Here's an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par return
return
Modules Cont…
 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 −
# Import module support
import support
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]]
Example:
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 *
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;
OUTPUT:
['__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']
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 −
CONT…
Packages in Python Cont…
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.
# 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
INPUT & OUTPUT