CHAPTER 5
USER DEFINED FUNCTIONS
Creating a Function
def xyz():
"this is about functions"
print('function')
return
print ('this is about functions')
xyz()
print ('done')
raw_input('any key ..')
Function with arguments
def xyz(a,b):
return (a+b)
import os
[Link]('cls')
a=int(raw_input('val1 '))
b=int(raw_input ('val2 '))
c=xyz(a,b)
print ('The sum is %d' % (c))
raw_input('any key ...')
Function with keyword
arguments
# keyword arguments
def test2(a,b):
return (a+b)
c=test2(a=100,b=200)
print (c)
raw_input('any key ')
Function with default
arguments
def test3(a,b=100):
return (a+b)
c=test3(200)
print (c)
raw_input ('any key ')
Function with local variables
def pqrst:
m=100
print (m)
return
m=1200
print (m)
Pqrst()
print (m)
raw_input ('any key ')
Function with variable length
variables
def test4(a, *pqr):
s=0
for x in pqr:
s=s+x
return(a+s)
r1=test4(10)
r2=test4(10,20,30)
r3=test4(1,2,3,4,5,6)
print (r1)
print (r2)
print (r3)
raw_input ('any key ')
Lambda Function
s=lambda x1,x2:x1+x2
print (s(100,200))
raw_input ('any key ')
Functional Programming Tools
There are three built-in functions that are
very useful when used with lists: filter(),
map(), and reduce().
filter(function, sequence) returns a
sequence consisting of those items from the
sequence for which function(item) is true.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
Functional Programming Tools
map(function, sequence) calls
function(item) for each of the sequence’s
items and returns a list of the return
values. For example, to compute some cubes
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729,
1000]
Functional Programming Tools
reduce(function, sequence) returns a single
value constructed by calling the binary
function function on the first two items of
the sequence, then on the result and the next
item, and so on. For example, to compute the
sum of the numbers 1 through 10:
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
Tabular Printing of the data
>>> from tabulate import tabulate
>>> print tabulate([["spam", 1], ["eggs",
42]])
---- --
spam 1
eggs 42
---- --
>>>print tabulate [[‘one’,1],[‘two’,2]],
[‘words’,’numbers’],’grid’))
CHAPTER 6
MODULES AND PACKAGES
What is a Module
A module is a file
consisting of Python
code. A module can
define functions,
classes, and variables
Creating a Module
[Link]
def a():
print ('prasad')
return
def b():
print ('raju')
return
def c():
print ('krishna')
return
Importing the Module
import m1
m1.a()
m1.b()
m1.c()
raw_input('any key ')
Importing specific functions
from the Module
from m1 import a
a()
raw_input('any key ')
Byte-compiling
• Python automatically byte-compiles
modules.
• Next execution does not require
compilation.
• .py files get a .pyc in the same
directory
• When the .py is updated, the .pyc is
updated
• Python is a compiled language but
not a native-compiled language: like
Java or C#
How Python finds
modules
• [Link] is the path which is traversed
when looking for a module (during an
import):
>>> import sys
>>> print [Link]
['directory1', 'directory2', 'directory3',
...]
• The search is sequential left to right
until success (or end is reached)
• Various ways to change it: PYTHONPATH
environment variable, Windows registry
tricks, special magic “.pth” files,
explicit code that modifies [Link].
Packages
A package is a hierarchical
file directory structure that
defines a single Python
application environment that
consists of modules and sub-
packages and sub-sub-
packages, and so on.
'
Packages
Consider a file [Link] available in
Phone directory. This file has
following line of source code:
def Pots():
print "I'm Pots Phone"
Packages
Similar way we have
another two files –
[Link] and [Link]
having the same function
names pots1() and pots2()
respectively
Packages
Now, create another file
__init__.py in phone
directory.
__init__.py should have,
From pots import pots()
From pots1 import pots1()
From pots2 import pots2()
Packages
Import Phone
[Link]()
Phone.pots1()
Phone.pots2()
CHAPTER 7
Regular Expressions
The Re Module
[Link]/[Link]
The function [Link] attempts to match
RE pattern to string which would be
searched to match the pattern at the
beginning of string.
The function [Link] searches for
first occurrence of RE pattern within
string
Both functions return a match object on
success, None on failure.
The Re Module
[Link]
import os,re
[Link] ('cls')
x='python programming'
m=[Link]('python',x)
if m:
print ('found')
print ([Link]())
else:
print ('not found')
raw_input ('any key ')
The Re Module
[Link]
import os,re
[Link] ('cls')
x=‘This is python programming'
m=[Link]('python',x)
if m:
print ('found')
print ([Link]())
else:
print ('not found')
raw_input ('any key ')
The Re Module
[Link]
findall returns a list of matches
import os,re
[Link] ('cls')
x='python programming and python testing'
m=[Link]('python',x)
if m:
print ('found')
print (m)
else:
print ('not found')
raw_input ('any key ')
The Re Module
[Link] (from a file)
import os,re
[Link] ('cls')
x=open('[Link]','r')
m=[Link]('is',[Link]())
if m:
print ('found')
print (m)
else:
print ('not found')
raw_input ('any key ')
The Re Module
[Link]
This method replace all
occurrences of the RE pattern in
string with repl, substituting
all occurrences unless max
provided. This method would
return modified string
[Link](pattern, repl, string, max=0)
The Re Module
[Link]
import os,re
[Link] ('cls')
x=open('[Link]','r')
m=[Link]('is','IS',[Link]())
if m:
print ('found')
print (m)
else:
print ('not found')
raw_input ('any key ')
The Re Module
re patterns
import os,re,sys
[Link] ('cls')
x=[Link]('.')
for a in x:
m=[Link]('^r',a)
if m:
print (a)
raw_input ('any key ')
The Re Module
re patterns (contd.)
import re,os
[Link]('cls')
x='The no is A123'
m=[Link](r'\w\d\d\d',x)
if m:
print([Link]())
raw_input ('any key ')
The Re Module
re patterns (contd.)
import re,os
[Link]('cls')
x='the no is A123'
m=[Link](r'A...',x)
if m:
print([Link]())
raw_input ('any key ')
CHAPTER 8
Python Standard
Library
Frequently Used Modules
os / [Link]
sys
shutil
datetime / dateutils
glob
zlib
OS Module
Many functions for interacting
with the operating system:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
OS / [Link]
[Link]()
[Link]() / [Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
Shutil / sys
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]
[Link]
[Link]
sys.ps1
[Link]
datetime Module
import datetime
x=[Link]()
print "Current date and time: " , x
Print [Link], [Link], [Link]
Print [Link], [Link],[Link]
print [Link]("%y-%m-%d-%H-%M")
date arithmetic
import datetime
today = [Link]()
print 'Today :', today
one_day = [Link](days=1)
print 'One day :', one_day
yesterday = today - one_day
print 'Yesterday:', yesterday
tomorrow = today + one_day
print 'Tomorrow :', tomorrow
date arithmetic
From dateutils import relativedelta as rd
from datetime import date
d1 = date(2001,5,1)
d2 = date(2012,1,1)
d3 = rd(d2,d1)
print "{[Link]} years and
{[Link]} months".format(d3)
'10 years and 8 months'
The glob Module
• glob module provides a function
for making file lists from
directory wildcard searches:
>>> [Link]('*.py')
['[Link]', '[Link]', '[Link]']
math Module
• The Usual Suspects:
acos (x) asin (x) atan (x) atan2(x, y)
ceil (x) cos (x) cosh (x) exp (x)
fabs (x) floor (x) fmod (x, y) frexp (x)
hypot (x, y) ldexp (x, y) log (x)
log10 (x) modf (x) pow (x, y) sin (x)
sinh (x) sqrt (x) tan (x) tanh (x)
• The module also defines two
mathematical constants:
pi = 3.14159265359 e = 2.71828182846
• cmath module defines same functions for
complex numbers.
>>> [Link](-2)
(0.69314718056+3.14159265359j)
The Random Module
>>> import random
>>> [Link](['apple', 'pear', '
banana'])
'apple‘
>>> [Link]()
0.17970987693706186 # random float
>>> [Link](6)
4
# random integer chosen from range(6)
The zlib Module
Data Compression
>>> import zlib
>>> s = 'witch which has which witche
s wrist watch’
>>> len(s)
41
>>> t = [Link](s)
>>> len(t)
37
>>> [Link](t)
'witch which has which witches wrist'