You are on page 1of 45

Programming Construct-2:

Functions, Packages & Modules,


Random, Idea of Efficiency,
Performance measurement in terms of
the number of operations.

Dr. Jasaswi Prasad Mohanty


Silicon Institute of Technology, Bhubaneswar
Functions
• A function is similar to a program that consists
of a group of statements that are intended to
perform a specific task.
• Types of Functions:
– Built-in Functions – Functions which are already
available in Python. Eg: print(), sqrt(), power() etc.
– User-defined Functions – Functions created by
programmer. Eg: isPrime(), display() etc.

6/30/2020 JPM/Silicon 2
Functions
• Advantages:
– Once a function is written, it can be reused as and
when required (Reusable Code). Programmer can
avoid code redundancy.
– Functions provide modularity for programming.
– Code maintenance will become easy.
– Use of functions in a program will reduce the
length of the program.
– In case of error in a software, corresponding
functions can be modified without disturbing
other functions.

6/30/2020 JPM/Silicon 3
Defining a Function
• Syntax: Starting of
function definition
Function Parameters Beginning of
funtion body
def functionName (para1, para2, . . . ):
""" function docstring """
Provides information
Function statements about the function
(optional)
• Example:
def sum (a, b ):
""" This function finds sum of two nos a and b"""
c=a+b
print(c)

6/30/2020 JPM/Silicon 4
Calling a Function
• Syntax:
functionName (para1, para2, . . . )
• Example:
sum (10, 5 )
• Program:
def sum (a, b ):
""" This function finds sum of two nos"""
c=a+b
print("Sum = ",c)
sum (10, 5 )
sum (1.5, 5.75)
• Output:
Sum =15
Sum=7.25

6/30/2020 JPM/Silicon 5
Returning Results from a Function
• We can return the results from a function
using a “return” statement.
• Example:
– return x
– return 10
– return lst
– return a, b, c

6/30/2020 JPM/Silicon 6
Returning Results from a Function
• Program:
def sum (a, b ):
""" This function finds sum of two nos"""
c=a+b
return c
s1=sum (10, 5 )
print("Sum = ",s1)
s2=sum (1.5, 5.75)
print("Sum = ",s2)
• Output:
Sum =15
Sum=7.25

6/30/2020 JPM/Silicon 7
Function to find the Factorial of a number

• Program:
def fact(n):
""" Function to find factorial of a number n"""
f=1
for i in range (1,n+1):
f=f*i
return f
no=5
fac=fact(no)
print("Factorial of " + str(no) + " = " + str(fac))
• Output:
Factorial of 5 = 120

6/30/2020 JPM/Silicon 8
Function to check a number is prime or not
• Program:
def isPrime(n):
""" Function to check a number n is prime or not"""
x=1
for i in range (2,n):
if n%i == 0:
x=0
break Output:
return x 97 is Prime.
no=97
p=isPrime(no)
if p==1:
print(str(no) + " is Prime.")
else:
print(str(no) + " is not Prime.“)
6/30/2020 JPM/Silicon 9
Returning multiple values from a Function

• Program:
def sum_diff (a, b ):
""" Function returns sum and difference of two nos"""
sum = a + b
diff = a - b
NOTE:
return sum, diff Unlike programming languages C or
x, y = sum_diff (10, 5 ) Java, in Python a function can return
print("Sum = ",x) multiple values.
print("Difference = ",y)
• Output:
Sum = 15
Difference = 5

6/30/2020 JPM/Silicon 10
Assigning a Function to a variable

• It is possible to assign function to a variable.


• Program:
def display(str):
return "Hello " + str
#assign function to a variable
x=display("Krishna")
print(x)
• Output:
Hello Krishna
6/30/2020 JPM/Silicon 11
Defining a Function inside another
Function
• It is possible to define one function inside
another function.
• Program:
def display(str):
def msg():
return "How are you? "
result = msg()+str
return result
print(display("Ram"))
• Output:
How are you? Ram
6/30/2020 JPM/Silicon 12
Pass by Object Reference
• Everything is considered as an object in Python.
– Numbers, strings, tuples, lists, dictionaries all are objects.
• In Python the values are sent to functions by means of
object references.
• When we write x = 10, one object 10 is created whose
name is x.
• Objects are created in heap memory which is available
during run time of a program.
• To know the location of object we can use id() function.
x=10
print(id(x)) # 140728342061744

6/30/2020 JPM/Silicon 13
Pass by Object Reference – contd…

• When we pass values (numbers, strings etc.) to a function,


reference of the objects are passed to the function.
• Program:
NOTE:
def modify(x):
Integer, float, string and tuple objects
x=15 are immutable.
print(x, id(x));
x=10
modify(x)
print(x, id(x))
• Output:
15 140728342061904
10 140728342061744

6/30/2020 JPM/Silicon 14
Pass by Object Reference – contd…

• Program:
def modify(lst):
NOTE:
lst.append(5) Lists and dictionary objects are
print(lst, id(lst)); mutable.
lst=[1, 2, 3, 4]
modify(lst)
print(lst, id(lst));
• Output:
[1, 2, 3, 4, 5] 2329173753224
[1, 2, 3, 4, 5] 2329173753224
6/30/2020 JPM/Silicon 15
Formal and Actual Arguments
• The parameters used in the function definition to
receive parameters outside the function are
called formal arguments.
• During function call we use some arguments,
which are called actual arguments.
• The actual arguments used in a function call are
of 4 types:
– Positional Arguments
– Keyword Arguments
– Default Arguments
– Variable length Arguments

6/30/2020 JPM/Silicon 16
Positional Arguments
• These are arguments passed to a function in correct
positional order.
• The number of arguments and their position in the
function definition should match with the number and
position of the arguments in the function call.
• Program:
def attach(s1,s2):
s3=s1+'-'+str(s2)
print ("Total string = "+s3)
attach('Cuttack',753004)
• Output:
Total string = Cuttack-753004
6/30/2020 JPM/Silicon 17
Keyword Arguments
• Keyword arguments are arguments that identify the
parameters by their names.
• Program:
def grocery(item, price):
print("Item = "+ item + " Price = "+str(price))

grocery(item='sugar',price=50.50)
grocery(price=80.00,item='oil')
• Output:
Item = sugar Price = 50.5
Item = oil Price = 80.0
• We can change the order of the arguments, as the parameter
names guide where to store the values.

6/30/2020 JPM/Silicon 18
Default Arguments
• We can specify some default value for the
function parameters in the definition.
• Program:
def grocery(item, price=40.00):
print("Item = "+ item + " Price = "+str(price))

grocery(item='oil', price=80.00)
grocery(item='sugar')
• Output:
Item = oil Price = 80.0
Item = sugar Price = 40.0
6/30/2020 JPM/Silicon 19
Variable Length Arguments
• A variable length argument is a argument which can accept one or more
number of values.
• It is used in the function definition in the case where the programmer
wants to develop a function that can accept one or more number of
arguments.
• Program:
Output:
def add(farg,*args):
Formal argument = 5
print("Formal argument = ",farg)
sum of all numbers = 15
sum=0
Formal argument = 1
for i in args:
sum of all numbers = 15
sum+=i
print("sum of all numbers = ",(farg+sum))
add(5,10)
add(1,2,3,4,5)

6/30/2020 JPM/Silicon 20
Recursive Function
• A function that calls itself is known as recursive function
• Program: Factorial of a Number
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
no=7
fac=fact(no)
print("Factorial of " + str(no) + " = " + str(fac))
• Output:
Factorial of 7 = 5040

6/30/2020 JPM/Silicon 21
Recursive Function
• Program: GCD of two Numbers
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
• Output:
Enter first number:15
Enter second number:20
GCD is:
5
6/30/2020 JPM/Silicon 22
Python Modules
• A module is a file containing Python definitions and
statements.
• A module can define functions, classes and variables.
• Grouping related code into a module makes the code
easier to understand and use.
• Example:
# A simple module, Calculation.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

6/30/2020 JPM/Silicon 23
The import statement
• We can use any Python source file as a module by
executing an import statement in some other
Python source file.
• When interpreter encounters an import
statement, it imports the module if the module is
present in the search path.
• To import the module calculation.py, we need to
put the import command at the top of the script :
import Calculation
print(Calculation.add(10,2)) #12
print(Calculation.subtract(10,2)) #8

6/30/2020 JPM/Silicon 24
The from import statement
• Python’s from statement lets you import
specific attributes from a module.
• The from … import ... has the following syntax:
# importing sqrt() and factorial() from the module math
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))

6/30/2020 JPM/Silicon 25
Renaming a module
• Python provides us the flexibility to import
some module with a specific name so that we
can use this name to use that module in our
python source file.
• Syntax:
import <module-name> as <specific-name>
• Example:
import Calculation as cal
print("Sum = ",cal.add(5,10))
6/30/2020 JPM/Silicon 26
Packages
• Packages are a way of structuring many
packages and modules which helps in a well-
organized hierarchy of data set, making the
directories and modules easy to access.
• Packages help us in storing other sub-packages
and modules, so that it can be used by the user
when necessary.

6/30/2020 JPM/Silicon 27
Creating and Exploring Packages
• To inform Python that a particular directory is a
package, we create a file named __init__.py inside
it.
• We may create other modules and sub-packages
within it. This __init__.py file can be left blank or
can be coded with the initialization code for the
package.
• Steps to create a Package:
1. Create a directory and specify some name as a
package name, preferably related to its operation.
2. Put the classes and the required functions in it.
3. Create an __init__.py file inside the directory, to let
Python know that the directory is a package.
6/30/2020 JPM/Silicon 28
Creating Packages: Example
• Create a new folder named 'MyApp' under the
current directory.
• Create an empty __init__.py file in the MyApp
folder.
• Inside MyApp, create a subfolder with the
name 'mypackage'.
• Create an empty __init__.py file in the
mypackage folder.

6/30/2020 JPM/Silicon 29
Creating Packages: Example
• Using a Python-aware editor like Spyder,
create a module functions.py with following
code:
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y

6/30/2020 JPM/Silicon 30
Creating Packages: Example-contd…
• So we have created the following structure:

6/30/2020 JPM/Silicon 31
Creating Packages: Example-contd…
• Now, to test the package, invoke the Python
prompt from the MyApp folder by creating a file
named ‘test.py’ under MyApp folder with the
following code:
from MyApp.mypackage import functions
print(functions.sum(3,2)) # Output 5
• It is also possible to import specific functions
from a module in the package. Change the test.py
code as follows and observe:
from MyApp.mypackage.functions import average
print(average(3,2)) # Output 2.5

6/30/2020 JPM/Silicon 32
Creating Random Numbers
import random #module to create random nos
# generates random numbers from 1 to 10
print(random.randint(1,10))
# generates random integer from 1 to 9
print(random.randrange(1,10))
# generates float values from 0 to 1
print(random.random())

6/30/2020 JPM/Silicon 33
Creating Random Numbers – contd…
import random
# generates random odd integers from 1 to 9
print(random.randrange(1,10,2))
# generates random evenintegers from 2 to 10
print(random.randrange(2,11,2))
# generates random numbers from a list
print(random.choice([1,2,3,4])

6/30/2020 JPM/Silicon 34
Algorithm Analysis
• To compare algorithms without implementing we
need to analyse them.
• It is a mathematical theory that helps a developer
to choose or design the right algorithm before
implementing a program.
• To analyse the algorithms we need some tools.
• The most important tool used to compare
algorithms are:
– RAM Model of Computation
– Asymptotic Analysis of worst-case complexity

6/30/2020 JPM/Silicon 35
Asymptotic Analysis
• Complexity of an Algorithm:
– The complexity or efficiency of an algorithm is
stated as a function (f(n)) relating the input
length(n) to the number of steps or storage
locations.
– The following two measures are used to compare
algorithms:
• Time Complexity: The number of key operations (e.g. no
of comparisons in case of sorting) need to be executed to
execute the algorithm.
• Space Complexity: The amount of computer memory
needed to execute the algorithm.

6/30/2020 JPM/Silicon 36
Asymptotic Notations
• The running time of an algorithm is said to be
asymptotic running time when the running time
is expressed in terms of input size (n) for a larger
value of n  .
• The notations we use to describe the asymptotic
running time of an algorithm are defined in terms
of functions whose domains are the set of natural
numbers N = {0, 1, 2, . . . }.
• The standard notations commonly used are: big-
oh(), big-omega(), theta(), little-oh(o) and
little omega().

6/30/2020 JPM/Silicon 37
Find the running time of the
following code:
a=0
b=0
m=int(input('Enter the value of m:'))
n=int(input('Enter the value of n:'))
for i in range(0,m):
a+=i
for i in range(0,n):
b+=i ANSWER:
O(m+n)
print(a)
print(b)

6/30/2020 JPM/Silicon 38
Find the running time of the
following code:
a=0
n=int(input('Enter the value of n:'))
for i in range(0,n):
for j in range(0,n):
a=a+i+j ANSWER:
O(n ) 2

print(a)

6/30/2020 JPM/Silicon 39
Find the running time of the
following code:
a=0
n=int(input('Enter the value of n:'))
for i in range(0,n):
for j in range(n,i,-1):
print(i,j) ANSWER:
O(n2)

6/30/2020 JPM/Silicon 40
Find the running time of the
following code:
k=0
n=int(input('Enter the value of n:'))
for i in range(int(n/2),n+1):
j=2
while(j<=n):
ANSWER:
k=k+n/2; O(n lg n)

j=j*2
print(k)
6/30/2020 JPM/Silicon 41
Selection Sort
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the minimum element with the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array") ANSWER:
for i in range(len(A)): O(n2)
print("%d“, A[i])
6/30/2020 JPM/Silicon 42
Bubble Sort
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
ANSWER:
print ("%d“,arr[i]) O(n2)

6/30/2020 JPM/Silicon 43
Find the running time of the
following code:
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
ANSWER:
O(lg n)

6/30/2020 JPM/Silicon 44

You might also like