Unit Iii
Unit Iii
Unit-3
Topics to be discussed:
List and Dictionaries: Lists, Defining Simple Functions, Dictionaries
Design with Function: Functions as Abstraction Mechanisms, Problem
Solving with Top Down Design, Design with Recursive Functions, Case Study
Gathering Information from a File System, Managing a Program’s Namespace,
Higher Order Function.
Modules: Modules, Standard Modules, Packages.
Introduction to Lists
A list is a sequence of data values called items or elements. An item can be of
any type. Here are some real-world examples of lists:
1
Python Programming (R19)
If the items in the list are literals then they will be put into resulting list
directly. If the items are variables or expressions, then their values after
evaluating them will be placed in the resulting string.
X=2
[x,math.sqrt(x)] -> [2, 1.41421]
We can use range() and list() functions to create a list of integers.
Example:
>>> L=list(range(1,6))
>>> L
[1, 2, 3, 4, 5]
We can use Concatenation (+) to combine two lists and equality (==)
to test whether two lists are same or not. We can use print() function to print
the list. We can use for() loop to iterate over the list items. We can use the ‘in’
and ‘not in’ membership operators to find some item is a member of a list or
not.
Replacing an Element in a List
The subscript operator is used to replace an element at a given position, as
shown below:
Lsit_name[position]=new_item
L[2]=30
List Methods for Inserting and Removing Elements
2
Python Programming (R19)
Searching a List
After elements have been added to a list, a program can search for a given
element. The ‘in’ operator can be used to determine whether an item is
present in the list or not. We have no find() method with list as it is present
with string methods.
Example Program:
L=[]
size=int(input('Enter the number of elements:’))
#reading elements into list
for i in range(size):
L.append(int(input('Enter next elemnt:')))
print('The List items are :',L)
element=int(input('Enter the element to search :'))
if element in L:
print(element, 'is found in the list')
else:
print(element,'Not found')
3
Python Programming (R19)
print('The elements of the stack are :',s) The stack after pop operation
s.pop() is: [3, 4]
print('The stack after pop operation is :',s)
Sorting a List
Although a list’s elements are always ordered by position, it is possible to
impose a natural ordering on them as well. In other words, you can arrange
some elements in numeric or alphabetical order. A list of numbers in
ascending order and a list of names in alphabetical order are sorted lists. The
list method sort() mutates a list by arranging its elements in ascending order.
Example: L.sort()
Mutator Methods and the Value None
Normally function or method returns a value to the caller when it is called,
the caller will use that value to complete its task. Some methods will change
the internal state of the object, but will not return any value. Such methods
are called Mutators. The list methods insert(), extend(), append(), and sort()
are all mutators. Python however automatically returns the special value
None even when a method does not explicitly return a value.
Example:
>>> x=L.sort()
>>> print(x)
None
4
Python Programming (R19)
5
Python Programming (R19)
the list [1, 3, 3, 5, 7] is 3, and the median of the list [1, 2, 4, 4] is also 3. The
following script inputs a set of numbers from a text file and prints their
median:
Median.py Output
l=[] Enter the number of
s=int(input('Enter the number of elements:5
elements:')) Enter number:4
for i in range(s): Enter number:2
l.append(int(input('Enter number:'))) Enter number:3
l.sort() Enter number:1
print('Print sorted of elements :',l) Enter number:7
if s%2!=0: Print sorted of elements : [1, 2,
m=len(l)//2 3, 4, 7]
print('Median is :',l[m]) Median is : 3
else: Mean is : 3.4
m=len(l)//2
print('Median is:',(l[m]+l[m-1])/2)
tot=sum(l)
avg=tot/len(l)
print('Mean is :',avg)
Tuples
A tuple is a type of sequence that resembles a list, except that, unlike a list,
a tuple is immutable. You indicate a tuple literal in Python by enclosing its
elements in parentheses instead of square brackets. Creating the tuple is
similar to the List. The only difference is, the items or elements that are
separated by comma are enclosed within parenthesis.
Syntax:
T=() Empty tuple
T=(2) Tuple with one element
T=(1,’apple’,2.34) Tuple with different elements.
We can put a tuple inside another Tuple, which also known as Nested Tuple.
Tuple operations and methods
We can find the length of the tuple using the len() function.
We can use min(), max(), and sum() functions on Tuple and list also.
We can perform concatenation operation between two tuples (t=t1+t2)
We can use membership operator in and not in on the tuple.
We can use for() loop to iterate over the tuple.
6
Python Programming (R19)
Sets
Set is another data structure in python. Sets are similar to the lists, with a
major difference that sets are lists with no duplicate entries. A set is created
by placing all the elements inside the curly brackets {}, separated by comma
operator.
Syntax:
S={item1,item2,item3,….itme n}
Example: S={1,2,4,5}
Operations on sets and methods
We can use min(), max(), and sum() functions on Tuple and list also. All the
set operations such as union, intersection, set difference, subset and superset
can be performed with various methods as Shown in the Table.
Methods Description
s.update(t) Adds elements of t to the set s
s.add(element) Adds element to the set
s.remove(element) Removes element from the set. Returns Error if the
element is not present
s.discard(element) Same as remove, but does not raise error if element is
not present.
s.pop() Removes an arbitrary element from the set
s.issuperset(t) Returns True if every element of t is present in set s.
s.intersection(t) Returns a new set that has elements common
elements of sets s and t
s.union(t) Returns a set s that elements from s and t
s.difference(t) Returns elements that are in s, but not in t
s.isdisjoint(t) Returns True if both sets are disjoint sets
7
Python Programming (R19)
Comprehension
Python includes more powerful advanced operation known as “list
comprehension expression”. Comprehension is powerful way to process the
structures like matrix. Comprehensions are used to create new_list by
running an expression on each item in a list or sequence from Left-to-Right.
Comprehensions can be written to list, tuple, sets, dictionaries and strings.
List comprehension
These are the ways to build new_list by applying an expression to each item
in the sequence.
Syntax: [ expression loop]
Example:
8
Python Programming (R19)
Tuple comprehension
These are similar to the list comprehension, but produce an object instead of
building a new list on demand. This object needs to be converted into list to
see result.
Syntax
T=(expression loop)
Example:
t=(i for i in range(2,21) if i%2==0)
Output:
<generator object <genexpr> at 0x0222CF60>
Convert it to list
l=list(t)
print(l) #output [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
t1=(i**2 for i in [1,2,3])
<generator object <genexpr> at 0x0222CF90>
l1=list(t1)
Print(l1) # output [1, 4, 9]
Introduction to Functions
Definition – A Function is a block of program statements that perform single,
specific and well-defined task. Python enables it’s programmers to break the
program into functions, each of which has some specific task. When a
function is called, the program control is passed to the first statement in the
function definition. All the statements in the function are executed in sequence
and the control is transferred back to function call.
The function that calls another function is known as “Calling
Function”, and the function that is being called by another function is known
as “Called Function”.
Uses of Functions
9
Python Programming (R19)
The first line is known as the function header. It marks the beginning of the
function definition. The function header begins with the key word def,
followed by the name of the function, followed by a set of parentheses with
parameters, followed by a colon (:). The function body contains one or more
statements. These statements are executed in sequence to perform the task
for which it is intended to define.
Example: square function
• Positional Arguments
• Keyword Arguments
• Default Arguments
• Variable length Arguments
10
Python Programming (R19)
Positional Arguments
When a function is called arguments in the function call are assigned to the
parameters in the function definition. Actual arguments are assigned to
formal parameters according to their position in the order from left to the
right. We need to remember the position or order of the formal parameters,
otherwise arguments may be assigned in wrong way.
Keyword Arguments
When we call a function with some actual arguments, these are passed to the
formal parameters in the function definition based on their position (in the
order). Python also allows functions to be called using the keyword arguments
in which the position (order) of the arguments can be changed. The values are
not copied according to their position, but based on their name.
Syntax:
The actual arguments in the function call can be written as follow:
function_name(Arg_name1=value1,Arg_name2=value2)
An argument that is written according to this syntax is known as “Keyword
Argument”. Lets us understand this with an example.
Default Arguments
Python allows functions to be called without or with less number of arguments
than that are defined in the function definition. The default value to an
argument is provided using the assignment (=) operator. If the same number
of arguments are passed then the default arguments are not considered. The
values of actual arguments are assigned or copied to formal arguments if
passed, default arguments are considered otherwise. Hence, the formal
arguments are overwritten by the actual arguments if passed.
Example:
def add(x=12,y=13,z=14):
t=x+y+z
11
Python Programming (R19)
Variable-length arguments
In some situations, it is not known in advance how many number of
arguments have to be passed to the function.
In such cases, Python allows programmers to make function calls with
arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable-length arguments, then the
function definition uses an asterisk ( *) before the formal parameter name.
Example:
#function definition
def var_len_arg(name,*args):
print ("\n name, “Hobbies are:”)
for x in args:
print(x)
#function call
var_len_arg("Suman","Cricket","Movies","Traveling")
12
Python Programming (R19)
def even(x):
if x%2==0:
return True
else:
return False
a=int(input('Enter any number:'))
#function call
b=even(a)
print(b)
def main():
a=int(input('Enter any number :'))
square(a)
def square(x):
'''Performs the Square of a number'''
print('The square of {} is {}'.format(x,x**2))
#main function calling
main()
Dictionaries
Lists, and tuples organize elements by position. This way of arranging
elements is useful when we want to fetch first, last and any other element in
the sequence. However, the position of the element in the sequence in some
applications is irrelevant. We are interested in association of an element with
some other element in the sequence. For example, looking up phone number
in the phonebook, we don’t care where it is present in the phonebook.
Dictionary Literals
13
Python Programming (R19)
fruits={}
fruits['apple']=125
fruits['mango']=300
fruits['orange']=250
print(fruits)
fruits['mango']=450 #replacing value at key
Accessing Values
You can also use the subscript to obtain the value associated with a key.
However, if the key is not present in the dictionary, Python raises an error.
Syntax:
>>> fruits['apple']
125
14
Python Programming (R19)
We can also use get() method of dictionary data structure for accessing
values as follow:
print(fruits.get(‘apple’,None)),
if the given key is present then it gives value, otherwise gives None.
Removing Keys
We can remove an entry or item from the dictionary using the pop() method
of the dictionary data structure. The pop() method takes key as an argument
and an optional default value as another argument. If the key is present it will
be removed an it value is returned. Otherwise default value will be returned.
If pop() is used with one argument, and key is absent then Python raises error.
fruits.pop('apple',None)
125
>>> fruits
{'mango': 450, 'orange': 250}
Traversing a Dictionary
When a for loop is used with a dictionary, the loop’s variable is bound to each
key in an unspecified order. Alternatively, you could use the dictionary
method items() to access a list of the dictionary’s entries or items. Syntax:
dob.items(), displays all the items as pair of key and value.
15
Python Programming (R19)
16
Python Programming (R19)
• If the sum() function does not exist, we need to write the sum function
multiple times in our program where ever we need summation.
• In other words redundant code would appear in the program.
• This code redundancy is bad for several reasons.
• Copy the same code and paste again and again and correct it if required.
• If a modification is required then all the instances of same code needs
to corrected.
• By using the single function definition just in one place called module,
we can avoid redundant code.
• Any other module or program can then import function for its use for
any number of times.
• When a programmer needs to debug, repair, or improve the function,
he/she needs to edit and test single function definition.
Functions Hide Complexity
def summation(low,upper):
s=0
while low<=upper:
s=s+low
low=low+1
print('Sum is:',s)
#function call
summation(4,8)
17
Python Programming (R19)
• The problem instances for our summation problem are numbers that
specify the lower and upper bounds of the range of numbers to be
summed.
• The problem instances may vary from program to program. For
example, summation(4,8), summation(12,20), summation(30,60).
• Here, the summation() functions provides both summation algorithm
and also problem instances.
• In other words, function is providing general method with systematic
variations.
Functions Support the Division of Labour
In a well-organized system, whether it is a living thing or something created
by humans, each part does its own job or plays its own role in collaborating
to achieve a common goal.
Specialized task are divided up and assigned to the specialized agents or
persons.
Some agents or persons may coordinate other tasks.
Good agents or persons can do their own business, and do not try to do job
of others.
A poorly organized system, by contrast, suffers from agents performing tasks
for which they are not trained or designed. Division of labor breaks down.
Functions can enforce a division of labor, which restricts each task
performing single, well defined, and special task.
18
Python Programming (R19)
Each box in the structure chart is labelled with a function name. The
main function at the top is where the design begins, and decomposition leads
us to the lower-level functions on which main depends. The lines connecting
the boxes are labelled with data type names, and arrows indicate the flow of
19
Python Programming (R19)
data between them. For example, the function countSentences takes a string
as an argument and returns the number of sentences in that string. Note that
all functions except one are just one level below main.
The Design of the Sentence-Generator Program
Here, you decompose the problem by simply following the grammar rules for
phrases. To generate a sentence, you generate a noun phrase followed by a
verb phrase, and so on. Each of the grammar rules presents a problem that
is solved by a single function.
Example: subject +verb +object (Simple present tense)
20
Python Programming (R19)
21
Python Programming (R19)
# Iterative algorithm
def displayrange(low,upper):
while low<=upper:
print(low)
low=low+1
#main function
l=int(input('Enter low value:'))
u=int(input('Enter upper value:'))
#Function Call
displayrange(l,u)
22
Python Programming (R19)
def displayrange(low,upper):
if low<=upper:
print(low)
displayrange(low+1,upper)
#main function
l=int(input('Enter low value:'))
u=int(input('Enter upper value:'))
#Function Call
displayrange(l,u)
23
Python Programming (R19)
Infinite Recursion
If a function continues to execute forever, this situation is known as
Infinite Recursion. Infinite recursion arises when the programmer fails to
specify the base case or to reduce the size of the problem in a way that
terminates the recursive process. The Python virtual machine keeps calling
runforever(1) until there is no memory left to support another recursive call.
Unlike an infinite loop, an infinite recursion eventually halts execution with
an error message.
24
Python Programming (R19)
def displayrange(low,upper):
if low<=upper:
print(low)
displayrange(low+1,upper)
#main function
l=int(input('Enter low value:'))
u=int(input('Enter upper value:'))
#Function Call
displayrange(l,u)
The stack frames for the process generated by displayRange(1, 3) are shown
in Figure:
• Although this sounds like a complex process, the PVM handles it easily.
• However, when a function invokes hundreds or even thousands of
recursive calls, the amount of extra resources required, both in
processing time and in memory usage, can add up to a significant
performance hit.
• When, because of a design error, the recursion is infinite, the stack
frames are added until the PVM runs out of memory, which halts the
program with an error message.
25
Python Programming (R19)
26
Python Programming (R19)
'''
files.py
author: Dr.KSR
Purpose: Menu-driven tool for navigating a file system.
'''
import os
QUIT='7'
COMMANDS=('1','2','3','4','5','6','7')
MENU="""
1 List the current working directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of directory in bytes
6 Search for a file
7 Quit the program"""
def main():
while True:
27
Python Programming (R19)
28
Python Programming (R19)
if not filelist:
print('File not found')
else:
for f in filelist:
print(f)
else:
print('Please choose correct command')
def listcurrentdir(dirname):
l=os.listdir(dirname)
for item in l:
print(item)
def moveup():
os.chdir('..')
def movedown(currentdir):
newdir=input('Enter subdirectory name:')
if os.path.exists(currentdir+os.sep+newdir) and os.path.isdir(newdir):
os.chdir(newdir)
else:
print('Error message: no such file')
def countfiles(path):
''' returns the number of file in the cwd and subdirectories'''
count=0
l=os.listdir(path)
for item in l:
if os.path.isfile(item):
count=count+1
else:
os.chdir(item)
count=count+countfiles(os.getcwd()) #recursion
os.chdir('..')
29
Python Programming (R19)
return count
def countbytes(path):
count=0
l=os.listdir(path)
for item in l:
if os.path.isfile(item):
count=count+os.path.getsize(item)
else:
os.chdir(item)
count=count+countbytes(os.getcwd()) #recursion
os.chdir('..')
return count
def findfiles(target,path):
files=[]
l=os.listdir(path)
for item in l:
if os.path.isfile(item):
if target in item:
files.append(item)
else:
os.chdir(item)
files.extend(findfiles(target,os.getcwd()))
os.chdir('..')
return files
#main function
main()
30
Python Programming (R19)
only, but not to the computer. The computer considers a variable as name
given to value stored in the computer memory. Let us learn how a program’s
name space which includes set of variables and their values are structured in
the program.
The variable in the program falls under any one of the following three
categories:
• When a variable comes into existence, storage is allocated for it; when
it goes out of existence, storage is reclaimed by the PVM.
• Module variable lifetime will be throughout the program execution.
• Parameters and temporary variables come into existence when function
is called, but go out of existence when the function call terminates.
31
Python Programming (R19)
Higher-order Functions
As we gain experience in writing the programs, we try to identify the
common and redundant patterns in the code.
One common pattern that occurs again and again is applying the
function to a set of data values to produce some results.
Examples
Converting all the numbers in text file or list to integers or floats
Putting grades in a list whose score is above average.
Computing sum of squares of a list of numbers.
Capturing these patterns in a new abstraction is called ‘Higher-
ordered function’.
32
Python Programming (R19)
33
Python Programming (R19)
>>> l
[1, 123, 100, 567]
Filtering -This is the second type of Higher-order function. In this
process, a function called a Predicate or Condition is applied to each
value in a list. If the predicate returns True, the value passes the test
and is added to a filter object like list. Otherwise, the value is dropped
from consideration. Python includes a filter function to perform this
task.
>>>def odd(n): return n%2==1
>>>l=list(filter(odd , range(1,10)))
>>> l
[1, 3, 5, 7, 9]
34
Python Programming (R19)
Note: These functions can be used in the scope where they have been defined,
once the scope is ended we cannot reuse them.
Modules
A module is a file that contains Python code. This code contains functions and
variables that perform related tasks. This approach is called “Modularization”. This makes the
program easier to understand, test and maintain.
Modules also make it much easier to reuse same code in more than one program. If we
have written set of functions that are needed in several different programs, we can place them
in modules. Then we can import these modules in each program to call one of the functions.
Creating Modules
For example we use the functions such as area of circle, circumference of circle, area
of rectangle and circumference of rectangle in many programs. So we can create two modules
such as: circle and rectangle, and put the functions related to the circle in that module and
functions related to the Rectangle in another module called rectangle. We can just import these
modules into any number of programs if their functions are needed.
Rules for Module Names:
✓ A module file name should end with .py. If it is not ended with .py we cannot import it
into other programs.
✓ A module name cannot be keyword.
✓ The module must be saved within the same folder (directory) where you are accessing
it.
When the Python interpreter reads this statement it will look for the file circle.py in the
same folder as the program that is trying to import it. If it finds the file it will load it into
memory. If it does not find the file, an error occurs.
35
Python Programming (R19)
import circle
x=float(input("Enter the Radius:"))
#function call to area
res=circle.area(x)
print ("The area of the Circle is:",res)
#function call to circum
res=circle.circum(x)
print ("The Circumference of the Circle is:",res)
There are Four ways of using import to import a module and subsequently use what was
imported. We will use the math module to illuminate:
# Way 1
import math
print math.cos(math.pi/2.0)
This method imports everything from the math module, and members of the module are
accessed
using dot notation.
#way 2
from math import cos
print cos(3.14159265/2.0)
This method imports only the dentition of cos from the math library. Nothing else is
imported.
#way 3
from math import cos, pi
print cos(pi/2.0)
36
Python Programming (R19)
This method imports only definitions of cos and pi from the math library. Nothing else is
imported.
#way 4
from math import *
print cos(pi/2.0)
This method also imports everything from the math module, the difference being that dot
notation is not needed to access module members.
circle.py module
#definition of area function from circle import*
def area(r): x=float(input("Enter the Radius:"))
a=3.14*r*r #function call to area
return(a) res=area(x)
#definition of circumference print ("The area of the Circle is:",res)
def circum(r): #function call to circum
c=2*3.14*r res=circum(x)
return(c) print ("The Circumference of the Circle
is:",res)
Namespacing
A namespace is a syntactic container which permits the same name to be used in
different modules or functions. Each module determines its own namespace, so we can use the
same name in multiple modules without causing an identification problem.
For example, functions such as area(r) and circum(r) are part of the module circle.py.
We can also use same names in another module like “cir.py”. These functions are called from
these module independently.
mod1.py testans.py
question="What is your name" import mod1
ans="Write your answer" import mod2
mod2.py q=mod1.question
print( "Question is:",q)
a=mod1.ans
print ("Answer is:",a)
q=mod2.question
37
Python Programming (R19)
Standard Modules
Python’s standard library is very extensive, offering a wide range of
facilities as indicated by the long table of contents listed below.
The library contains built-in modules (written in C) that provide access
to system functionality such as file I/O that would otherwise be
inaccessible to Python programmers, as well as modules written in
Python that provide standardized solutions for many problems that
occur in everyday programming.
Some of these modules are explicitly designed to encourage and
enhance the portability of Python programs by abstracting away
platform-specifics into platform-neutral APIs.
More than 200 core modules sit at the heart of the standard library.
But in addition to this library, you can also access a growing collection
of several thousand components from the Python Package Index (PyPI).
Some modules are as follows:
✓ numbers — Numeric abstract base classes
✓ math — Mathematical functions
✓ cmath — Mathematical functions for complex numbers
✓ decimal — Decimal fixed point and floating point arithmetic
✓ fractions — Rational numbers
✓ random — Generate pseudo-random numbers
✓ statistics — Mathematical statistics functions
38
Python Programming (R19)
39
Python Programming (R19)
Packages
When the number of modules (simply stated, a module might be just a
file containing some classes) in any project grows significantly, it is
wiser to organize them into packages – that is, placing functionally
similar modules/classes in the same directory.
Steps to Create a Python Package
Working with Python packages is really simple. All you need to
do is:
Create a directory and give it your package's name.
Put your modules in it.
Create a __init__.py file in the directory
That's all! In order to create a Python package, it is very easy. The
__init__.py file is necessary because with this file, Python will
know that this directory is a Python package directory other than
an ordinary directory.
40
Python Programming (R19)
Introduction to PIP
So far we have been working with package that we have created and is in our system.
There may be situation where we want to install packages that are not in our system and created
by others residing in other system. This can be done using the PIP tool.
The Python Package Index is a repository of software for the Python programming
language. There are currently1,25,120 packages here. If we need one package we can
download it from this repository and install in our system. This can be performed using the PIP
tool.
41
Python Programming (R19)
The PIP command is tool for installing and managing the packages, such as found in
Python Packages Index repository (www.pypi.python.org). To search for a package say
numpy, type the following:
To uninstall package we can use the pip tool as follow: pip uninstall numpy in the command
prompt.
42
Python Programming (R19)
import numpy as np
m1=np.array([[1,2,3],[4,5,6],[7,8,9]])
m2=np.array([[1,2,3],[4,5,6],[7,8,9]])
mat_add=np.add(m1,m2)
print(mat_add)
Output:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
import numpy as np
m1=np.array([[3,4,5],[14,15,16],[17,18,19]])
m2=np.array([[1,2,3],[3,2,1],[5,6,7]])
mat_sub=np.subtract(m1,m2)
Output:
matrix subtraction is
[[ 2 2 2]
[11 13 15]
[12 12 12]]
import numpy as np
m1=np.array([[1,2,3],[4,5,6],[7,8,9]])
m2=np.array([[1,2,3],[3,2,1],[5,6,7]])
mat_mul=np.multiply(m1,m2)
Output:
[[ 1 4 9]
[12 10 6]
[35 48 63]]
43
Python Programming (R19)
import numpy as np
m1=np.array([[1,2,3],[4,5,6],[7,8,9]])
m2=np.array([[1,2,3],[3,2,1],[5,6,7]])
mat_mul=np.dot(m1,m2)
Output:
matrix mul is
[[22 24 26]
[49 54 59]
[76 84 92]]
44