Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
221 views

Python - User Defined Functions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
221 views

Python - User Defined Functions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

User Defined Functions

What is Function?

A function is a named block of organized,


reusable set of statements to perform a specific task.

It contains line of code(s) that are executed


sequentially from top to bottom by Python Interpreter
Why To Use Function?
• Reusability of code reduces code redundancy that improves
programmer’s efficiency
• Functions make a program compact
• A compact program is easier to maintain
• Testing and correcting errors is easy because errors are
localized and can be corrected easily
• Using Function modular programming can be achieved
Types Of Functions
Built-in Functions Defined User Defined
Function In Modules Function (UDF)

predefined A module is a file A function defined


functions that are containing by a programmer
already available functions and to do a specific
in Python variables task
How to Define UDF

Defining UDF involves two steps

Writing • contains the statements


Function which is responsible for
Definition performing the task

• executes the statements


Invoking/calling
User Defined given within a function
Function
Writing Function Definition
Two parts of Function Definition:

Function Header Function Body

It includes the
keyword def, It includes the
function name , statements to perform
parameters lists and the required action
a:
Syntax Of Function Definition
Key word to Identifier as a parameters supplied to a :The : marks
Function name function to be manipulated end of header
define Function

def fun_name([parameter1, parameter2…..]) :


””” Docstring
Statements to be executed Function
Body

[return statement]
Components Of Function Header
• Keyword ‘def’ marks the start of Function header
• The function name is an identifier which uniquely
identifies the function
• The parameters refer to the data items which are
passed to the function to work on it.
• The colon : marks the end of Function header which
also means it requires a block.
Assessment
Built in functions are also called___________

Answer : Predefined functions

A function defined by a user to do a specific task is called __________

Answer : User defined function

____________ part of function contains the statements responsible for


performing a task.

Answer : Function definition

The function name is an example of __________ type of token


Answer : Identifier
Assessment
The keyword _______ marks the start of Function header
Answer : def

A function header includes __________ along with __________

Answer : Function name, parameters

The statement to execute a user defined function is called________

Answer : Function call statement

The data items which are passed to the function to work on it are
referred as ___________.

Answer : Parameter
Examples Of Function Definition

#calculate area of a Triangle


def area(b,h):
ar = 1/2*b*h
return ar

# To display first 10 even nos


def fun_even():
for i in range(2,21,2):
print(i)
Syntax of Function Call
A function call statement is given to execute the statements
given within a function

Function name which is


Data supplied to a function to call
definition is given before

Function_name(argument1, argument1…)
In a Python program, the function definition should be
present before it’s call statement.
Parameters and Arguments
Parameters refer to the objects that are listed within the parentheses
after the function name in a function header of the Function Definition.
Parameter is also referred as Formal Parameter
The values being passed through the function call statement are called
Arguments or Actual Parameter.
The argument passed in the function call statement is received in
corresponding parameter given in .
The arguments given in Function call statement must match the no.
and order of parameters in function Definition. This is called Positional
Argument Matching
Difference between Parameters and Arguments
Parameters refer to the objects that are listed within the parentheses
after the function name in a function header of the Function Definition.
Parameter is also referred as Formal Parameter
The values being passed through the function call statement are called
Arguments or Actual Parameter.
The argument passed in the function call statement is received in
corresponding parameter given in .
The arguments given in Function call statement must match the no.
and order of parameters in function Definition. This is called Positional
Argument Matching
Difference between Parameters and Arguments

Parameters Arguments

Parameters refer to the Arguments are the values


objects that are listed within being passed through the
the parentheses in a function call statement
function header of the
Function Definition.

These are also referred as These are also referred as


Formal Parameter Actual parameters

Parameters can be objects Arguments can be data items,


only objects or expressions
Parameters and Arguments
#calculate area of a Triangle
b and h given in function
def area(b,h): header are parameters
ar = 1/2*b*h
return ar
ba=float(input(“Enter base-”))
h=float(input(“Enter height -”)) ba and h given in function call
ar=area(ba,h) are argument

print(“area-”,ar)
12 and 10 given in function call
print(“area-”,area(12,10)) are argument
print(“area-”,area(ba/2,h*2)) Ba/2 and h8 given in function
call are argument
Examples Of Function Call
#calculate area of a Triangle
def area(b,h):
ar = 1/2*b*h
return ar
# To display first 10 even nos
ba=float(input(“Enter base-”)) def fun_even():
h=float(input(“Enter height -”)) for i in range(2,21,2):
ar = area(ba,h) #Fun call statement print(i)
print(“area-”,ar)
fun_even() #Fn call statement
print(“area-”,area(12,10))
print(“area-”,area(ba/2,h*2))
Examples Of UDFs

#functions calculate area & perimeter


def area(rad):
return 3.14*rad**2 # To display n no. of Fibonacci series
def peri(rad): def fun_fib(f, s, n):
p= 2*3.14*rad print(f,”\t”,s)
return p for i in range(3,n+1):
rad = float(input(“Enter radius - ”)) th = f+s
ar = area(rad) #Fn call statement print(“\t”,th)
print(“area-”,ar) f,s=s,th
print(“perimeter - ”,peri(rad)) f =int( input(“First no –”))
s =int( input(“Second no –”))
n =int( input(“No. of Terms–”))
fun_fib(f, s, n) #Fn call statement
Examples Of UDFs
Write a program with functions calcsal() and calcdesig(). The function calcsal() takes basic salary as
parameter and calculates deduction as 5.5% of basic salary, allowance as 12% of basic salary and net
as basic salary + allowance – deduction
The function calcdesig() takes net salary as parameter and assigns designation as manager if net
salary > 100000, Executive if net salary <100000 and >=50000 and Non executive if net salary <50000
def calcdesig(net):
if net >= 100000:
desig = “Manager"
elif net >= 50000
desig = "Executive"
else:
desig = "Non Executive“
return desig
def calcsal(basic):
d = 5.5/100*basic
all = 0.12*basic
net = basic + all – d
print("Designation = ",calcdesig(net))
basic = float(input(" enter basic Salary - " )
calcsal(basic)
Examples Of UDFs
Write a program with a Function checkchar() which takes a character
as parameter and checks whether the character is an alphabet / digit or
Special Character
def checkchar(ch):
if ch >= "0" and ch <= "9":
res = "digit"
elif ch >="a" and ch <= "z" or ch >= "A" and ch <= "Z":
res = "alphabet"
else:
res = "Special character"
return res
ch = input("enter a Character -")
print(checkchar(ch))
Examples Of UDFs
Write a program with a Function checkchar() which takes a character
as parameter and checks whether the character is an alphabet / digit or
Special Character
def checkchar(ch):
if ch >= "0" and ch <= "9":
return "digit"
elif ch >="a" and ch <= "z" or ch >= "A" and ch <= "Z":
return "alphabet"
else:
return "Special character"
ch = input("enter a Character -")
print(checkchar(ch))
Example : User Defined Function
Write a program using UDF which takes x and n as parameters and
calculates x to the power of n.
def power(x,n):
prod=1
for i in range(1,n+1):
prod*=x
print("x to the power of n",prod)

n = int(input("Enter n value"))
x = int(input("Enter x value"))
power(x,n)
Structure Of A Python Program
In a Python Program, generally all function definitions are given at
the top followed by all the statements which are not part of any
function. These statements are called Top-level statements.
By default, Python names the segment with top-level statements as
__main__.
The __main__ segment is not indented at all.
The program execution starts from the first statement of __main__
segment
Structure Of A Python Program
def area(b,h):
ar = 1/2*b*h
return ar
ba=float(input(“Enter base-”))
h=float(input(“Enter height -”)) __main__ segment
ar= area(ba,h))
print(“area –”,ar)

While dry running a program, you should start with the first
statement of _main_ segment and then transfer the control the
function definition of a function as and when it is called.
Examples Of UDFs
Write a menu driven program using UDF which takes n1 and n2 as parameters and prints all
even,odd and prime numbers between n1 and n2. Write UDF for each option.
def even(n1,n2):
for i in range(n1,n2+1): def odd(n1,n2):
if i%2 == 0: for i in range(n1,n2+1):
print(i,sep="\t") if i%2 == 1:
n1 = int(input("Enter n1 -")) print(i,sep="\t")
n2 = int(input("Enter n2 -")) def prime(n1,n2):
while True: for i in range(n1,n2+1):
ch = int(input("1.even\n2.Odd\n3.Prime\n Enter choice")) for j in range(2,i//2+1):
if ch==1: if i % j ==0:
even(n1,n2) break
elif ch==2: else:
odd(n1,n2) print(i," - Prime")
elif ch==3:
prime(n1,n2)
else:
print("Wrong choice")
ans = input("want to continue (y/n)")
if ans in "Nn":
break
Example of a program with user defined functions
Write a menu driven program to Reverse a number, Count number of digits present in the
number and Check if the number is Armstrong or not
def checkarmstrong(n):
sum = 0
def revno(n):
def countdig(n): num = n
rev = 0
cnt = 0 while n > 0:
while n > 0:
while n > 0: dig =n%10
dig = n%10
dig = n % 10 sum += dig**3
rev = rev*10 + dig
cnt += 1 n //= 10
n //= 10
n //= 10 if num == sum:
print("Reverse no -", rev)
print("No of digits:",cnt) print(num, “ armstrong no")
else:
print(num," not an armstrong no")
ch=int(input("1:To find reverse \n2:count digits\n3:check for choice")
num=int(input("Enter the number"))
if ch==1:
revnumber(num)
elif ch==2:
countdig(num)
elif ch==3:
checkarmstrong(num)
else:
print("Wrong choice given")
Example : Function call in a menu driven program
Write a menu driven program to accept an integer and do the following on user's choice
1. multiplication Table 2. Factors 3. Check Prime or Composite -
Write UDF for each option
def multtable(num): def prime(num):
for i in range(1,11): for i in range(2,num//2):
print(num," * ",i," = ",num*i) if num%i==0:
print(num," is composite")
def factors(num):
break
for i in range(1,num+1):
else:
if num % i ==0:
print(num," is prime")
print(i)

num=int(input("\nEnter number-"))
ch=int(input(" \n1.multiplication Table\n2. Factors\n3.Prime/Composite - "))
if ch==1:
multtable(num)
elif ch==2:
factors(num)
elif ch==3:
prime(num)
Types of Function

Non-void Function Void Functions


Function returning some Function not returning any
value value

def area(b,h): def fun_even():


ar = 1/2*b*h for i in range(2,21,2):
return ar print(i)
Return Statement in Non Void Function
The return statement in a non void function can be used to
• return an object ,
• Return a data item or an expression
• return in a Non void function control back to that part of the program where it is
called with the processed data. To return control only return is used.
When return statement is not given in an UDF or only return is given without anything
to transfer the control, Python returns None
Example : Function to calculate quotient
Program : def quotient(num,deno):
if deno==0:
print("division not possible")
return #Returns None and control returns
else:
return (num // deno) #Returns expression
n1 = int(input("enter num1 - "))
n2 = int(input("enter num2 - "))
print(“Calculated quotient” , quotient(n1,n2))
Return Statement in Non Void Function
Write an UDF to calculate factorial of an integer. The UDF should consider the validation
for –ve number and returns calculated factorial for 0 and non zero positive integer.
def factorial(num): #Function to calculate factorial
if num<0:
print(“number is negative ")
return #Returns control
elif num==0:
return 1 #Returns Data item
else:
res=1
for i in range(1,num+1):
res*=i
return res #Returns object
n=int(input ("Enter number-"))
res = factorial(n) #when n is 0 or +ve
If res = = None:
print("Factorial can’t be calculated)
else:
print("Factorial=",res)
Return Data in a Void Function
A void Function may or may not have a return statement.
When a void function has a return statement it is given as only to
transfer control and will return None.
A void function always returns a value None. So It can also be used as
lvalue of an assignment statement or in print statement.

Example
Output
def wishme(name):
print(“Hello”,name)
nval=wishme("Anisha") Hello Anisha
print(nval) None
print(wishme(“Nishi")) Hello Nishi
None
Example: Function call within another function
WAP to Calculate the sum of the following series using function:
X2/2! - X4/4! +X6/6!………Xn/n!
Write function factorial() to calculate factorial and sum_series() which will call factorial() to
calculate the sum. Input x and n from user.

def factorial(n): def sum_series(x,n):


f=1 sum=0
for i in range(1,n+1): sign=1
f*=i for i in range(2,n+1,2):
return f f = factorial(i) # call to factorial()
sum += ((x**i) / float(f)) * sign
sign*=-1
return sum

x = int(input("enter value of x-"))


n = int(input("enter value of n-"))
if n%2 == 1:
n -= 1
print("sum = ",sum_series(x,n)) # function call
Flow Of Execution in a Python Program
Flow Of execution refers to the order in which the statements are
executed during program execution
When Python encounters a function definition, Python just executes
the function header and checks it’s correctness.
Execution always begins from the first statement of the _main_
segment
When a function call statement is encountered, the control jumps to
the called function and executes the statement given in that function.
With the return statement or the last statement of the function the
control comes back to the point where it is called.
Flow Of Execution in Python Program

Last statement of
function will send the
def area(b,h): control back to where it
is called
ar = 1/2*b*h
return ar
ba=float(input(“Enter base-”))
h=float(input(“Enter height -”))
Function call statement
transfers control to ar= area(ba,h))
Function Definition print(“area –”,ar)
From the program code given below, give the order of
execution of code?
def power(radius): #1
return radius**2 #2
def area(r): #3 Order of execution–
a=3.14*power(r) #4 1->3->6->7->3->4->1->2->4-
return a #5 >5->7
rad=float(input(“Enter radius “)) #6
print(area(rad)) #7
Assessment
The segment with top level statements in Python is referred as
__________

Answer : __main__

______________refers to the order in which the statements are executed


during program execution

Answer : Flow Of execution

The return statement in a ________function returns a non-empty


value
.
Answer : Non-void
Assessment
When a return statement is used without anything, it returns
a. int
b. float
c. None
d. None of the above

Answer : c None

The _______ keyword marks the beginning of a function block.


a. func
b. def
c. define
d. None of the above
Answer : b def
Assessment
Which of the following are present in a function header statement ?
a. Function name only
b. Both function name and parameter list
c. Parameter list only
d. Return value

Answer : b. Both function and parameter list

The values being passed by the function call statement are called___________
a. parameters
b. arguments
c. Return values
d. None of the above
Answer : b arguments
User Defined Function returning multiple values
A python User defined function can return multiple values
When multiple values are returned each returned value is separated
by comma.
Syntax : return value1, value2….
values returned can be a literal or object or expression
When a function returns multiple values,
- the function call statement can either display it by using print
statement or
- receive the returned values by giving required number of objects
on the left side of function call statement
- Or by receiving in form of a tuple
Example : Function returning multiple values
Example - Write a program using UDF which accepts seconds as parameter and
converts seconds to its equivalent hours, minutes and seconds . The
converted hours, minutes and seconds should be returned from the
function.

Program - def convertsec(sec):


hr = sec // 3600
sec = sec % 3600
min = sec // 60
sec = sec % 60
return hr, min, sec #Multiple objects returned
seconds = int(input("Enter seconds value"))
h, m, s = convertsec(seconds) #Fun call statement
print("The converted hours,minutes and seconds are:",h,m,s)
In the above example in the function call statement objects h, m and s are used to
receive the calculated result
The calculated data returned by the UDF can also be stored in a tuple using the
statement - sect = convertsec(seconds)
print("The converted hours,minutes and seconds are:",sect)
Assessment
Give output if the following program
def outp():
for i in range(3,5):
if i==4:
i+=5
for j in range(4,0,-1):
print(j*i,end=’*’)
print()
outp()

Answer : 12*9*6*3*
36*27*18*9*
Assessment
Give output if the following program

def change(n):
f, s=n%10,n%100
while n!=0:
r=n%10
if r%2!=0:
f%=r
else:
s+=r
n//=10
return f,s
f, s = change(1234543)
print(f, s)

Answer : 0 53
Example : Function returning multiple values
Write a program using UDF to calculate sum , average ,maximum and minimum values
from a set of n number of numbers where n is given as parameter and return all these
values .
def calcres(n):
sum, avg, max, min = 0,0,0,0
max = int(input("Input First number - "))
min = max
sum += max
for i in range(1,n):
num = int(input("Input no"))
sum += num
if num > max:
max=num
num < min:
min = num
avg = sum/n1
return sum, max, min, avg
n = int(input("Input n number of numbers "))
sum, max, min, avg = calcres(n)
print(“ sum = ",sum,“ avg = ",avg,“ max = ",max,“ min = ",min)
Q Give the output of the following code:
def outp():
for i in range(3,5):
if i==4: Output
i+=5 j 12*9*6*3*
for j in range(4,0,-1): 36*27*18*9*
print(j*i,end=’*’)
print()
outp()
Q Give the output of the following code:
def calc(x):
for i in range(1,3):
for j in range(1,i):
z= i+j-1
print(z,end=' ') Output
if z%2 == 0: j
2 6
z=x+2 2 8
elif z%3==0:
z=x+3
print(z)
calc(4)
calc(6)
Give the output of the following code:
def incr():
a=7
b=2
for i in range(4,17,6):
if i% 8 == 0: Output
a+=5 7 3
j
print (a,b+1) 7 7
if b%2==0:
12 11
b+=4
else:
b*=4
incr()
Q Give the output of the following code:
def calc(x,y):
return 2*x+y
Output
def execute(a,b): 3
for i in range(1,a): j
4
for j in range(1,b): 5
print(calc(i,j))
execute(2,4)
Give the output of the following code:
def calc(u):
if u%2==0:
return u+10 10 *
else: 2*
j
return u*2 10 @
def pattern(ch,n): 2@
for cnt in range(n):
print(calc(cnt),ch)
pattern("*",2)
pattern("@",2)
Give the outputs given by the following two codes. Also mention the type of
functions (void or non-void),they belong to, along with justification.
def calc(a,b): #code 1
sum=0
for k in range(a,b+1):
if k%3==0:
j Output
prod=2*k**2
90
sum+=prod Non-void function
return sum
print(calc(2,6))

def calc(a,b): #code 2


sum=0
for k in range(a,b+1):
if k%3==0: Output
prod=2*k**2 j None
sum+=prod Void function

print(calc(2,6)
Q Rewrite the following code after removing the
syntactical error(s), if any.
def chktot
x = int(input(“Enter a number”))
if x%2 = 0: def chktot():
for k in range(2 * x): x = int(input(“Enter number”))
print(i) if x%2 == 0:
Else: for k in range(2*x):
print(“#”) j print(i)
else:
print(“#”)

chktot()
Q Rewrite the following code after removing the
syntactical error(s), if any.
def checkval:
x = input(enter number)
def checkval():
if x%2=0: x = int(input(enter number))
print x,”is even” if x%2== 0:
print (x,”is even”)
else if x<0:
elif x < 0:
print(x , ”should be positive”) print(x , ”should be positive”)
else: else:
print (x, ”is odd”)
print( x, ”is odd”) checkval()
Q Rewrite the following code after removing the
syntactical error(s), if any.
def tot(number)
sum=0 def tot(number) :
for c in Range(1,number+1): sum = 0
sum+=c for c in range(1,number + 1):
sum+=c
return sum j
return sum

print(tot[5]) print(tot(5))
Rewrite the following code after removing the syntactical
error(s), if any.
def sum(i,j)
x = int(input(enter x)) def sum(i,j):
return (i * j + x) x = int(input(“enter x”))
def Main(): return (i * j + x)
def Main():
k=sum(i,j) k = sum(4,5)
Main() Main()
Q Give the output of the following code:
def fact(d):
s=0
i=d
while i>=1:
if d%i ==0:
s+=i Output
j
i-=1 23
return s
def extract(n):
s=0
while n!=0:
d=n%10
s+=fact(d)
n//=10
return s
print(extract(436))
List of programs
1. Accept a number from the user and Write a menu driven program using UDFs to do the
following :
a Count the number of even ,odd and zero digits in it
b Display the maximum and minimum digit
c Find sum and average of all digits
All functions should return the results
2. Input two numbers n1 and n2 and Write a menu driven program using UDFs to do the
following :
a Count the number of prime in it
b Count the number of perfect numbers in it
c Count the number of palindromes in it
All functions should return the results
3. WAP to Calculate the sum of the following series using function:
5!/X2 – 7!/X3 +9!/X4……(2n+1)!/Xn
Input x and n from user.
Write function factorial() to calculate factorial and sum_series() which will call factorial() to
calculate the sum.
Q From the program code given below, give the order of
execution of code?(Number:721)
def maxdigit(n): #1
print(n) #2
max=n%10 #3
while n>0: #4
dig=n%10 #5 Order of execution(with number 721)
if dig>=max: #6 1->10->17->18->10->11->1->2->3->4->5-
max=dig #7 j >6->7->8->4->5->6->7->8->4->5->6->7-
n//=10 #8 >8->4->9->11->12->14->15->16->18->19
return max #9
def checkeven(num): #10
d=maxdigit(num) #11
if d%2==0: #12
even=1 #13
else: #14
even=0 #15
return even #16
number=721 #17
S=checkeven(number) #18
print(S) #19
Mutable and Immutable Datatypes Of Python
Python Data Types

Mutable Data types Immutable Data types

CAN BE changed in place CAN NOT BE changed in place


Example : List, Dictionary Example : int, float, string, tuple
Immutable Objects in Python
• Objects of Immutable data type does not allow
the initialization of the value of the object in the
same memory location.
• When Immutable object is reassigned with a
value, Python allocates new memory location
to store the changed value.
Mutable Objects in Python
• Values for objects of Mutable data types can be
changed in the same memory location after their
assignment or creation.
• When the value of a mutable object is changed its
memory is not reallocated. Hence, the object refers to
the same memory location after re-initialization of it’s
value
Mutable and Immutable Properties Of Argument & Parameter

When arguments are passed to functions :


• The caller function always pass the reference
(memory address) of the argument to the called
function.
• The caller and the called function refer to the same
memory location where the parameter and argument
is stored.
• when any statement of the called function change the
value of the Parameter, the behavior of parameters
and argument depends on their mutability /
immutability of the object
Immutable as Parameter to User Defined function
• When a function is called with objects of immutable data types like int,
float, bool, tuple or string value as argument, the parameter to receive
the value is created in the function header of UDF. As the argument and
parameter refer to the same data item, ids of both are same (i.e both
refer to the same memory address).
• When any statement given inside the body of the called function,
attempts to change the parameter, the id of the parameter object will
change as it will refer to a new memory address where the changed
data get stored. The Parameter object with new memory location remain
accessible only to the statements present inside the UDF.
• As the re-assignment of value of Parameter is happening in a different
memory location, when control leaves the UDF, the value of argument
remain unchanged.
• Therefore, the block where the function call is taking place will not
notice any changes made to the immutable object inside the function
body.
immutability feature of parameter
def fun(pnum):
print("\nvalue of parameter before value change -“pnum)
print("id of parameter before value change -",id(pnum))
pnum+=100 #statement to change vale of pnum
print("\nvalue of parameter after value change -",pnum)
print("id of parameter after value change -",id(pnum))
num=100
print("value of argument before function call -",num)
print("id of argument before function call -",id(num))
fun(num)
print("value of argument after function call -",num)

Output : value of argument before function call - 100


id of argument before function call – 1634663904
value of parameter before value change – 100
id of parameter before value change - 1634663904
value of parameter after value change - 200
id of parameter after value change - 1634665504
value of argument after function call - 100
immutability feature of parameter
def fun(pnum):
print("\nvalue of parameter before value change -",pnum)
print("id of parameter before value change -",id(pnum))
pnum+=100 #statement to change vale of pnum
print("\nvalue of parameter after value change -",pnum)
print("id of parameter after value change -",id(pnum))
num=100
print("value of argument before function call -",num)
print("id of argument before function call -",id(num))
fun(num)
print("value of argument after function call -",num)

• When value of parameter pnum is changed in the fun() function, because of


immutability feature of int data type, the id of parameter pnum will change
• In Python, data types like integer, float, string and tuple are immutable objects.
• This means the value of argument of integer, float, string or tuple is not changed
in the calling block if the value of corresponding parameter is changed inside the
function or method block.
immutability feature of parameter
Give Output of the following
def func1(p,q):
p *= q Output
18#3
q = p//q 18#5
p = p+q 95#5
print(p,q,sep='#') 18#95
return p
p=3
q=5
p = func1(p,q)
print(p,q,sep='#')
q=func1(q,p)
print(p,q,sep='#')
String Object as Parameter and argument

• Strings in Python are sequences of character data represented as


UNICODE character.
• String literals may be delimited using either single or double quotes
or triple quotes for multiline string.
• The String data type is an example of Immutable data type of python
which implies when attempt is made to change an existing String
object, Python will display an error.
• Example : str = "Python“
str[3] = "H“
Python will result TypeError: 'str' object does not support item
assignment
String Object as Parameter to User Defined function
Write a program to define a UDF which will take a string and a character as
parameters . The function should Count and display the number of times a
character is appearing in a string.

def count(str, ch):


cntch=0
for chc in str:
if chc == ch : # check for user given character
cntch+=1
print("no of times character appears",cntch)

s=input(“Enter string”)
ch=input(“Enter a character”)
count(s,ch)
String Object as Parameter to User Defined function
Write a program to define a function which takes a string as parameter. Count and
return the number of alphabets, digits and special characters present in the string.
def count(str):
cnta = cntd = cntsp = 0
for ch in str:
if ((ch >= 'a' and ch <= 'z') or (ch>='A' and ch<='Z')):
cnta+=1
elif ch>='0' and ch <= '9':
cntd+=1
else:
cntsp+=1
return cnta,cntb,cntsp

s = input(“Enter string”)
cnta,cntb,cntc = count(s)
print("no of alphabets",cnta)
print("no of digits",cntd)
print("no of special char",cntc)
String Object as Parameter to User Defined function
Write an UDF to encrypt the string on the basis of given criteria and print the encrypted string
Every letter and digit should be replaced by the next, 9 should be replaced by 0 and Z/z should be
replaced by A/a. All space should be changed to *. All other special character should remain
unchanged. The function should take the string as parameter and return the encrypted string.
def encrypt(str):
newstr = ""
for ch in str:
newch = ch
if ch.isalnum():
if ch == "z":
newch = "a"
elif ch == ‘Z’:
newch = "A"
elif ch == "9":
newch = "0"
else:
newch = chr(ord(ch) + 1)
elif ch.isspace():
newch = "*"
newstr +=newch
print(newstr)
str = input("Enter the string -")
encrypt(str) #function called
String Object as Parameter to User Defined function
Write a program to define a UDF which takes a string as parameter. The function
should count and return the number of words which are starting with a consonant

def countwords(str):
cnt = 0
for ch in str.split():
if ch[0] >= 'a' and ch[0] <= 'z' or ch[0]>='A' and ch[0]<='Z' :
if ch[0] not in "AEIOUaeiou":
cnt+=1
return cnt

str1=input("Enter string")
print(countwords(str1))
String Object as Parameter to User Defined function
Write a program to define a UDF which takes a string as parameter .
The function returns the count of all words having number of
characters more than 5.

def countword(str):
count = 0
for ch in str.split():
if len(ch) >= 5 :
print(“Words with length more than 5”,ch)
count += 1
return count

str = input("Enter a string")


print(countword(str))
String Object as Parameter to User Defined function
Write a program to define a UDF which takes a string as parameter and
checks whether it is a palindrome or not. The function should return 1 if
palindrome otherwise 0.

def checkpalin(str):
if str == str[::-1]:
return 1
else:
return 0

str1 = input("Enter string")


chk = checkpalin(str1)
if chk == 1:
print("It is a palindrome")
else:
print("It is not a palindrome")
String Object as Parameter to User Defined function
Write a program to define a UDF which takes a string as parameter
.The function should return the count of all the palindromes in it.

def countpalin(str):
count=0
for ch in str.split():
if ch == ch[::-1]:
count+=1
return count

str=input("Enter a string")
print(countpalin(str))
String Object as Parameter to User Defined function
Write a program to define a UDF which takes a string as parameter.
The function should replace the first letter of all words starting with a
lowercase vowel to uppercase and display the changed string
def replace(str):
str1,str2='‘ , ‘'
for ch in str.split():
if ch[0] in "aeiou":
str1=chr(ord(ch[0])-32)+ch[1:]
else:
str1=ch
str2+=str1+‘ '
return str2

str=input("Enter a string")
print("Converted string:",replace(str))
String Object as Parameter to User Defined function
Write a program to Input a string and write equivalent codes in a user defined function
for functions: a. len() b. tolower() c. isalnum()
def length(str): def chlower(str):
l=0 newstr = ""
for ch in str: for ch in str:
l +=1 if ch >= "A" and ch <= "Z":
print("length",l) newstr += chr(ord(ch)+32)
else:
newstr += ch
print(newstr)
String Object as Parameter to User Defined function
Write a program to Input a string and write equivalent codes in a user defined function for
functions: a. len() b. tolower() c. isalnum()
def chkisalnum(str):
valid=True
for ch in str:
if not( ch >= 'A' and ch<='Z' or ch >= 'a' and ch<='z' ):
if not (ch>='0' and ch<='9'):
valid=False
print(valid)
ch = int(input("1:upper\n2:lower\n3:check isalnum\nEnter choice"))
s = input("Enter string")
if ch==1:
len(s)
elif ch==2:
chlower(s)
elif ch==3:
chkisalnum(s)
else:
print("Wrong choice")
Give the output of the following code:
def fun1(str1):
newstr=" "
for ch in str1:
if ch in 'a','e','i','o','u','A','E','I','O','U'):
newstr=newstr
else:
newstr+=ch
return newstr
# function ends here
str2= “aetopu”
print("Original ",str2)
str3=fun1(str2)
print(“Changed”,str3)

Output
Original aetopu
Changed tp
Give the output of the following code:
def execstr(Data)
Data2 = ' '
for i in range(len(Data) -1):
if Data[i].isupper() :
Data2+=Data[i].lower()
elif Data[i].isspace() :
Data2+= Data[i+1]
print( Data2)

str='Do It @123!'
execstr(str)

Output
dli@
Give the output of the following code:
def exex(string1):
string2 = ' '
for i in range(len(string1)):
if string1[i].isupper():
string2 += string1[i].lower()
elif string1[i].isdigit():
d = int(string1[i])+2
string2 += str(d)
elif string1[i].isspace():
string2 += string1[i+1]
else:
string2 += string1[i-1]
print(string2)

string = "SylLaBUS Exam2021"


exex(string)

Output sSylLbusEeExa4243
Give the output of the following code:
def calc(Msg1):
Msg2 = ""
for I in range(0,len(Msg1)):
if Msg1[I] >= "A" and Msg1[I] <= "Z":
Msg2 += Msg1[I].replace(Msg1[I],Msg1[I]*2)
elif Msg1[I] >= "a" and Msg1[I] <= "z":
if I%2 == 0:
Msg2 += chr(ord(Msg1[I+1])+1)
else:
Msg2 += Msg1[I].upper()
elif Msg1[I].isdigit():
Msg2 += str(int(Msg1[I])-1)
else:
Msg2 += '*'
print(Msg2)
Str = "WelcOME 123"
calc(str)

Output WWEdCOOMMEE*012
Give the output of the following code:
def outp(msg1):
msg2 = " "
for i in range(0,len(msg1)):
if msg1[i].isupper():
msg2 += msg1[i].lower()
elif i%2 == 0:
msg2 += "*"
else:
msg2 += msg1[i].upper()
print(msg2)
msg = "CompiLation"
outp(msg)

Output cO*P*l*T*O*
List object as parameter
• Lists are sequence data type where each element can be accessed using index
• List is heterogeneous in nature i.e the elements of a list are of mixed data type.
• List is Mutable which implies the changes can take in place in each index .
Example – lobj = [“Computer”,70,30,”083”]
lobj[1] = 100
• List elements can be accessed either moving left to right (using 0 to positive
index) or right to left (using negative index from -1).
Example – print(lobj[1], lobj[-2]
Output – Computer 30
• An empty list can be created assigning the list object to [] or by using list()
Example – lst = [] or lst = list()
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list and number of elements n as
parameters. The function should return the count of all zeroes, even and odd
elements in it
def countevenodd(list1,n):
cntzero,cnteven,cntodd = 0,0,0
for i in range(n) :
if list1[i] == 0:
cntzero += 1
elif list1[i] % 2 == 0:
cnteven += 1
else:
cntodd += 1
return cntzero, cnteven, cntodd

l1 = []
n = int(input("Enter number of elements of list"))
for i in range(n):
l1+= [int(input("Enter elements"))]
nzero,neven,nodd= countevenodd(l1,n)
print(nzero,neven,nodd)
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list and number of elements n as
parameters. The function should return the sum of all prime elements in it

def sumprime(list1,n):
sump=0
for i in range(n) :
if list1[i] == 1 or list1[i]==0:
print("It is neither prime nor composite")
continue
j=2
while j<=list1[i]//2:
if list1[i] % j ==0:
break
j+=1
else:
sump+=list1[i]
return sump
l1=[]
n=int(input("Enter number of elements of list"))
for i in range(n):
l1+=[int(input("Enter elements"))]
print(“sum:”,sumprime(l1,n))
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list ,number of elements and a
number to be searched as parameters. The function should return the position of the
number in list, if found otherwise should return -1, if not found.
def searchlist(list1,n,num):
for i in range(n) :
if list1[i] == num:
return i
else:
return -1
l1 = []
n = int(input("Enter number of elements of list"))
for i in range(n):
l1+= [int(input("Enter elements"))]
num = int(input(“Enter the number to be searched”))
pos = searchlist(l1,n,num)
if pos >= 0:
print(“Number found at “,pos+1, “position”)
else:
print(“Number not found in the list”)
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list as parameter. The
function should return the list with reversed contents.

def rev(list1):
list1 = list1[::-1]
return list1

l1 = eval(input("Enter list elements:"))


print("Original list:",l1)
revlist = rev(l1)
print("Reversed list:",revlist)
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list and the position from where an
element is to be deleted as parameters. The function should return the changed list.

def dellist(list1,pos):
i = pos-1
n = len(list1)
while i < n-1:
list1[i] = list1[i+1]
i+=1
list1 = list1[0:n-1]
return list1
l1 = eval(input("Enter list elements"))
Pos = int(input("Enter the position where number is to be deleted"))
print("originall list",l1)
lst = dellist(l1,pos)
print("Changed list",lst)
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list as parameters. The function
should replace each element having even value with its half and each element having
odd value (except first value) with double of its previous position element , and then
display the changed list.
Example:The original list is: [6, 7, 8, 9]
The changed list is: [3, 6, 4, 8]
def replacelist(list1,n):
for i in range(n):
if list1[i]%2==0:
list1[i]//=2
elif list1[i]%2 !=0 and i!=0:
list1[i]=list1[i-1]*2
l1=[]
n=int(input("Enter number of elements of list"))
for i in range(n):
l1+=[int(input("Enter elements"))]
print(“Original list:”,l1)
replacelist(l1,n)
print(“Changed list:”,l1)
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list num and its number of elements
as parameters. The function should exchange the values of first half side elements
with the second half side elements of the list.
Example: If a list of eight elements has initial contents as: 2,4,1,6,7,9,23,10
The function should rearrange the list as: 7,9,23,10,2,4,1,6
def replacelist(num,n):
i, j=0,(n+1)//2 #first half of the list starts at num[0], and
#second half starts at num[(n+1)//2]
while j<s:
list1[i], list1[j] = list1[j], list1[i]
i+=1
j+=1
l1=[]
n=int(input("Enter number of elements of list"))
for i in range(n):
l1+=[int(input("Enter elements"))]
print(“Original list:”,l1)
replacelist(l1,n)
print(“Changed list:”,l1)
List Object as Parameter to User Defined function
Write a program to define a UDF inslist which takes a list list1 ,position and number
num to be inserted as parameters. The function should insert the number num in the
specified position in list. Display the contents of the changed list

def inslist(list1,num,pos):
list1+=[0]
i = len(list1)-1
while i >= pos:
list1[i]=list1[i-1]
i -= 1
list1[pos-1] = num #new element inserted
l1=eval(input("Enter list elements"))
pos=int(input("Enter the position where number is to be inserted"))
num=int(input("Enter the number to be inserted"))
print("originall list",l1)
inslist(l1,num,pos)
print("Changed list",l1)
List Object as Parameter to User Defined function
Write a program to define a UDF change which takes a list num and its number of elements as
parameters. The function should replace each even element of the list with the sum of its digits
and each odd element with the product of its digits. For example, if the list is given as:
[100, 43, 20, 56, 32, 91, 80, 40, 45, 21]
After executing the program, the list content should be changed as follows:
[1, 12, 2, 11, 5, 9, 8, 4, 20, 2]
def change(num,n):
for i in range(n):
if num[i]%2==0:
s=0
while num[i]:
s+=num[i]%10
num[i]//=10
else:
s=1
while num[i]:
s*=num[i]%10
num[i]//=10
num[i]=s
l1=eval(input("Eneter elements of list"))
n=len(l1)
change(l1,n)
print("Changed list:",l1)
List Object as Parameter to User Defined function
Write a program to define a UDF which takes a list as parameter. The
function should add all those values in the list SCORES, which are
ending with five(5) and display the sum.
For example,
if the SCORES contain [200,456,300,105,235,678]
The sum should be displayed as 340

def SCORES(list1):
sum = 0
for k in list1:
if k%10 == 5:
sum += k
print("Sum of all numbers ending with 5:",sum))
L1 = eval(input("Enter list elements"))
SCORES(l1)
Give the output of the following code:
def listout1(L1,L2):
for p in range(1,-1,-1):
L1[p]+=L1[p+1]
for p in range(2,-1,-1):
L2[p]+=L2[p+1]

List1=[2,3,4]
List2=[10,20,30,40]
listout1(List1,List2)
print(List1)
print(List2)

Output
[9, 7, 4]
[100, 90, 70, 40]
Give the output of the following code:
def listout2(nums):
for i in range(1,6):
if i in nums:
index = nums.index(i)
c = nums.count(i)
print(i,'appears in nums',c,'times.',end=' ')
print('Its first occurence is at index',index)
Nums = [1,2,5,1,5,5]
listout2(nums)

Output
1 appears in nums 2 times. Its first occurence is at index 0
2 appears in nums 1 times. Its first occurence is at index 1
5 appears in nums 3 times. Its first occurence is at index 2
Give the output of the following code:
def listout3(L1,L2):
L3=[]
for j in range(len(L1)):
L3.append(L1[j]+L2[j])
L3.extend(L2)
return L3
L1,L2=[],[]
for i in range(20,10,-3):
L1.append(i)
for j in range(5,15,3):
L2.append(j)
L3=listout3(L1,L2)
print(L3)

Output
[25, 25, 25, 25, 5, 8, 11, 14]
Give the output of the following code:
def listout4(List1):
Tout=0
Alpha=' '
Add=0
for C in range(1,6,2):
Tout=Tout + C
Alpha = Alpha + List1[C-1]+'$'
Add=Add + List1[C]*2
print(Tout,Add,Alpha)
L1=['X',5,'Y',6,'Z',8]
listout4(L1)

Output
9 38 X$Y$Z$
Give the output of the following code:
def exec(list2):
for i in range(0,len(list2)):
list2[i]+=i
print(list2[i], end=' ')
print()
for i in list2[::-1]:
print(i, end=' ')
print()
list2.insert(2,5)

list1 = [30,10,50,20,80]
print(list1)
exec(list1) Output
print(list1) [30, 10, 50, 20, 80]
30 11 52 23 84
84 23 52 11 30
[30, 11, 5, 52, 23, 84]
Give the output of the following code:
def out(A,B):
B.extend(A)
A.insert(1,5)
print(A)
print(B)
for i in A:
if i in B:
B.remove(i)

A1=[y for y in range(3,6)]


B1=[-y for y in range(3,6)]
out(A1,B1)
print(A1,B1)

Output
[3, 5, 4, 5]
[-3, -4, -5, 3, 4, 5]
[3, 5, 4, 5] [-3, -4, -5]
Rewrite the following code in python after removing all syntax
error(s).Underline each correction done in the code
A=[3,2,5,4,7,9,10]
S=0
For m IN range(6):
if A[m] %2 = 0
S=+A[m]
print(S)

Corrected code:

A=[3,2,5,4,7,9,10]
S=0
for m in range(6):
if A[m] %2 == 0:
S+=A[m]
print(S)
Rewrite the following code in python after removing all syntax
error(s).Underline each correction done in the code
A = [3,2,5,4,7,9,10]
S=0
For m IN range(6):
if A[m] %2 = 0
S =+A[m]
print(S)

Corrected code:

A=[3,2,5,4,7,9,10]
S=0
for m in range(6):
if A[m] %2 == 0:
S+=A[m]
print(S)
Tuple Object as Parameter
• Tuples are sequence data type where each element can be accessed
using index
• Tuples are heterogeneous in nature i.e the elements of a tuple are of
mixed data type.
• Tuples are IMMUTABLE which implies the changes cannot take in
place
Example – tobj = (“Computer”,70,30,”083”)
tobj[1] = 100 # will give error
• Tuple elements can be accessed either moving left to right (using 0 to
positive index) or right to left (using negative index from -1).
Example – print(tobj[1], tobj[-1]
Output – 70 ‘083’
• An empty tuple can be created assigning the tuple object to ( ) or by
using tuple()
Example – tup = ( ) or tup = tuple( )
Tuple Object as Parameter
Program :
def change_tuple(t):
Newt = ()
for ele in t:
if type(ele) == int or type(ele) == float:
if ele%2 == 0:
Example : newt += (ele+1,)
Write an UDF which takes a tuple else:
element as parameter and change newt += (ele-1,)
element following criteria : elif type(ele) == str:
• If the element is float or integer newt += (ele.upper(),)
replace it with the next number. elif type(ele) == bool:
• If the element is Boolean data type, if ele == True:
replace all True with False and ele = 1
False with True. else:
• If the element is String, convert it to ele = 0
upper case newt += (ele,)
else:
newt += (ele,)
return newt
Dictionary Object as Parameter

• Dictinary data type of Python is a Mutable data type i.e new


element can be added and value of an exiting element can be
changed at the same memory location.
• Python Dictionary is an unordered collection of elements where
each element is a key-value pair.
• The element of dictionary can be accessed by its key field using
the syntax : dictionary_name[keyfield]
• An empty disctionary can be created assigning the dictionary object
to {} or by using dict()
Example – d1 = {} or d1 = dict( )
Dictionary Object as Parameter
WAP to create a dictionary trainer with
trainer-id as key field and name, def count(trainer):
experience, salary as value field (stored ctr=0
as a list). Input the trainer data from the for tno in trainer:
user and assign salary on the basis of if triner[tno][1] > 20 :
experience as follows: ctr +=1
Experience Salary def searchid(trainer):
>=10 70000 tn = int(input("Enter trainer id"))
<10 and >=5 50000 for tno in trainer:
<5 30000 if tno == tn:
print("Details are“)
Write a menu driven program to do the print(trainer[tno][0],trainer[tno][1],trainer[tno][2])
following: break
i Count the number of trainers whose else:
experience is more than 20 years print("id not found")
ii Display the details of trainer given
trainer id . Display appropriate
message if trainer id is not found
Write UDF for each option
Dictionary Object as Parameter
WAP to create a dictionary trainer with
trainer = { }
trainer-id as key field and name,
n = int(input("Enter number of elements"))
experience, salary as value field (stored
for i in range(n):
as a list). Input the trainer data from the
tid = int(input("Enter trainer id"))
user and assign salary on the basis of
name = input("Enter name")
experience as follows:
exp = int(input("Enter experience"))
Experience Salary
if exp >=10:
>=10 70000
salary =70000
<10 and >=5 50000
elif exp < 10 and exp <=5:
<5 30000
salary = 50000
Write a menu driven program to do the
elif exp < 5:
following:
salary = 30000
i Count the number of trainers whose
trainer[tid] = [name,exp,salary]
experience is more than 20 years
ch = int(input("1:count on name\n2:search on id"))
ii Display the details of trainer given
if ch == 1:
trainerid . Display appropriate message
count(trainer)
when trainerid is not found
elif ch==2:
searchid(trainer)
Write UDF for each option
else:
print("Wrong choice")
Passing arguments To UDF
Parameters are the values that are defined or used inside parentheses in the
function header of a function definition.
Arguments are the values that are passed to the function at run-time in the
function call statement so that the function can do the designated task using
these values.
Python supports 3 methods to pass the argument to a function

Methods of Passing arguments

Positional arguments Default arguments Keyword arguments


Positional arguments
• In Positional Argument method, the arguments are passed to a
function in correct positional order from left to right and order of
parameter cannot be changed .
• In Positional Argument method, the number of arguments in the
function call statement should match exactly with the parameters
given in the header of function definition.
• As the arguments are required to be given for all parameters, it is
also known as Required Parameters Method.
• As NO argument can be skipped from the function call, this method
is also referred as Mandatory Argument Method.
Positional arguments
Example : Write a python function multiple to display all multiples of 5
between two numbers given as parameters
Program : def multiple(n1,n2):
for i in range(n1,n2+1):
if i%5 == 0:
print (i )
num1= int(input("Enter first number"))
num2 = int(input("Enter second number"))
if num1>num2:
num1,num2=num2,num1
multiple(num1,num2)) #statement 1
• Using Positional argument method, n1 will refer to the value given by num1
and n2 will refer to the value given by num2.
• if the function call statement is given as multiple(num2,num1), then the
function will not generate any output as in that case n1 will refer to num2 and
n2 will refer to num1 and loop will not execute.
• Similarly, If the function is called using only num1, Python shall result in an
error.
Default arguments
In Default method of parameter passing
• default value(s) is assigned to a function’s parameter in the
function definition. An assignment operator ‘=’ is used to assign a
default value to a parameter.
• In parameters list, default values can be given to one or more
parameters.
• The default value is used when, required number of argument is
not given in the function call statement.
• In absence of argument, the function picks up the default value of
the missing argument.
• When the required number of argument(s) is passed, the actual
arguments will overwrite the default argument values.
Default arguments
Example : Write a UDF to calculate factorial of an integer given as
parameter. If the parameter is not given then it should
calculate factorial of 1.
Program : def factorial(num = 1): #default value 1 is assigned
res, i = 1,1
while i<=num:
res*=i
i+=1
print(res)
factorial() #Argument is omitted, Output will be 1
factorial(5) #Argument is given, Output will be 120(=5!)
• When argument is omitted in Function call, num is assigned with 1 (default
value) .
• When argument is given, the argument will overwrite the parameter.
Default arguments
A Python function can have a combination of default and non-default
parameters at the same time.
In a function definition, any parameter cannot have a default value unless all
parameters appearing on its right have their default values.
Example : Write a UDF divide which will take two integers as parameters
and display the quotient. If the second integer is not given, the
function should consider 1 as denominator
Program : def divide(num,deno=1): #default value 1 is assigned to deno
print(num//deno)
divide(5) #Output is 5 as deno will be 1 (the default value)
divide(17,2) #output is 8 as 2 will overwrite on the default value
Note : Python will result in an error If the function definition is given as :
def divide(deno=1,num): #default parameter is given before non default
print(num//deno)
Keyword Argument
In Key word argument, any argument can be given in any order
provided the name of the argument is given in function call statement.
Syntax Of Passing Key word argument : function name(keyword =
value)
• the keyword is the parameter name
• value is the value or object passed to the function
In Key word argument method :
• The arguments are given in any order in the function call statement.
• Name of the parameter (key word) is used instead of its position in
function call statement.
• The name of the keyword arguments should must match to one of
the parameter name given in the function header.
• The value of an argument can not be specified more than once.
Keyword Argument
Example : Write a python function to calculate area of a triangle
Program : def areatriangle(a,b,c):
s=(a+b+c) / 2
area = pow(s*(s-a)*(s-b)*(s-c),0.5)
print("Area is:",area)
areatriangle(b=5,a=20,c=10)

Advantages of Keyword argument


• With Keyword argument, Using the function is easier since it is not required
to remember the order of the arguments.
• The arguments can be rearranged in a way that makes them most
readable
• The arguments are called by their names which make it more clear what
they represent.
Mixed Argument Type
In Python UDF, positional and keyword arguments can be combined in a function
call statement.
When a combination of positional and keyword arguments is given
• the argument list must first contain positional argument
• followed by keyword argument. Otherwise it will result a syntax error
Example : Write a function to calculate simple interest
Program : def intcalc(p,r,t=10):
return p*r*t/100
print(intcalc(10000,r=5,t=7)) #statement 1
print(intcalc(t=5,10000,r=7)) #statement 2 – Illegal
In statement 1,
• the first argument value 10000 is representing a positional argument which will
be assigned to the first parameter on the basis of its position (which is p).
• The second and third argument t=5 and r=7 are representing the keyword
argument.
The statement 2 is an illegal statement as the positional argument is given after
the keyword argument
Assessment
Given a code as shown below ,State the output ,if correct, otherwise
mention the type of error given by each call statement:
def intcalc(p,r,t=10):
return p*r*t/100
1. t=8
print(intcalc(10000,r=5,t))
Answer : Error: non-keyword argument after keyword
argument
2. t=8
print(intcalc(100,t))
Answer : 80.0

3. t=8
print(intcalc(100,t,r=3)
Answer : TypeError: intcalc() got multiple values for argument 'r'
Assessment
Give the output of the following:
def execute(x,y = 200):
temp = x+y
x += temp
if y != 200:
print(temp,x,y)
else:
print(temp+x+y)
a,b = 50,20
execute(b)
execute(a,b)

Output : 660
70 120 20
Assessment
Give the Output of the following
def Execute(M):
if(M %3 == 0):
return M * 3
else:
return M +10

def output(B = 2):


T=0
while T < B:
print(Execute(T),end = "*")
T += 1
output(4)
output()
output(3)

Output : 0*11*12*9*0*11*0*11*12*
Scope and Lifetime Of Object In Python Program
• The Scope of an object decides as to how an object can be accessed
by the different parts of a program.
• The part of a program where an object is accessible to be used and
manipulated is referred as its scope.
• Scope rules of python are the rules which decide in which part of a
program an object can be accessed and used.
The Lifetime of an object refers to the period throughout which the
variable exits in the memory of the Python program. The scope of an
object decides it’s lifetime.
There are broadly 2 kinds of scope.
 Global Scope
 Local scope
Every Scope of Python holds the current set of objects and their values.
Global Scope
• An object declared in Top level segment i.e __main__ segment of a
program is said to have Global scope.
• When any object is created outside of all functions (before and after
the function definitions) then it is considered as “global Object”.
• Global object can be accessed by all statement in the program file,
including the statements given within any function and within any other
block.
• Any changes made to a Global object in any portion of a program is
permanent and visible to all the functions present in the program file.
• A global variable is created when the program execution starts and is
destroyed when the program terminates.
• As the Global objects are available through out the life time of a
program i.e life time of Global object is File run.
Global Scope
Example : To demonstrate Global Scope
Program : gnum1=100 #Global Object
def fun(n):
n += gnum1+gnum2 #global objects used
print("Changed value of n -",n)
gnum2 = int(input("enter a number :")) #Global Object
fun(10)

• Two global objects gnum1 and gnum2 are created


• gnum1 is assigned with 100 and gnum2 is assigned with user given
value.
• The function fun is called with argument 100 and parameter n is
assigned with the value 100.
• The global objects gnum1 and gnum2 are used inside the function.
The sum of gnum1 and gnum2 is added to the value of n
Local Scope
• Objects created inside a function ( or a block) is said to have Local
Scope.
• An object that is defined in a function or block is available in that
block only i.e it is not accessible outside the block. Such an object
is called a local object.
• Parameters declared in the function header of a function definition
behave as local objects.
• Local objects exist while the function is getting executed.
• Local Objects are created when control enters the function and get
destroyed when control comes out of the function.
• Hence, the function does not retain the value of an object from it’s
previous call.
Lifetime of the Local object is till the function is active or being
executed (i.e. function run) and scope is inside the function.
Local Scope
Example : To demonstrate Local Object
Program : def fun(n):
n += gnum
print("Changed value of n -",n)
gnum = int(input("enter a number :"))
fun(10)
In the above example, the global object gnum is used inside the function fun() to
change the value of Local object n.
Note : Any attempt to use a local object outside its scope will result in a
NameError.
Example : def fun(n):
n += gnum
print("Changed value of n -",n)
gnum = int(input("enter a number :"))
fun(10)
print("n=",n) #results error as n is used beyond it’s scope
Assignment of local object inside UDF
• Inside a UDF a global object can be accessed/printed directly.
• Whenever any assignment is attempted on a global object inside UDF,
Python creates a new local object and assignment is done on that Local
object.
• Hence, when any assignment is made to a local object inside the UDF the
change will not reflect back when control leaves the function.
Example : def checknum():
num = 100 #assignment of the local object
num = int(input("Enter A number -")) #global object num
checknum()
print("changed num -",num)
Output : Enter A number - 37
changed num - 37
global keyword
• To modify the global object inside the UDF, global key word is required to be
used before the object name.
• Without the global key word, the assignment will not alter the value of the
global variable.
Example : Write a program to input a number. Double the number if it is
even and half it if it is odd
Program : def checknum():
global num # St 1 - global is used to change num
if num%2 == 0:
num *= 2
else:
num //= 2
num = int(input("Enter A number -")) #global object num
checknum()
print("changed num -",num)
Output : Enter A number -37
changed num - 18
Assessment
Consider the function definition of calvolume()
def calvolume(pi, rad = 5, h = 10):
print(“volume – “,pi * r**2 * h)
Find out which of the following function call statements are valid/invalid.
Justify your answer based on the different methods of passing
parameters
a. calvolume(3.14)
Answer : Correct
b. calvolume(h=8,pi=3,rad=6)
Answer : Correct (named argument)
c. calvolume(3.14,rad=3)
Answer : Correct (mixed Argument)
d. calvolume(r1,pi=3)
Answer : Incorrect
e. calvolume()
Answer : Incorrect
Assessment
Consider the function definition of calvolume()
def calvolume(pi, rad = 5, h = 10):
print("volume – ",pi * r**2 * h)
Find out which of the following function call statements are valid /
invalid.
Justify your answer based on the different methods of passing
parameters
f. calvolume(h = 3,r1)
Answer : Incorrect
g. calvolume(h = 12,pi = 3)
Answer : Correct
h. calvolume(h = 20)
Answer : Incorrect
Assessment
Give suitable terms for the following descriptions based on the different
methods of passing parameters .
i. An object created inside function body
Answer : Local Object
ii. An object defined outside all function definitions
Answer : Global Object
iii. A value assigned to a parameter in function header statement
Answer : default value Object
iv. A value assigned to an argument in function call statement
Answer : Named argument
v. A value passed to call a function
Answer : argument
Assessment
Give the output of the following Give the output of the following
num = 100 def func1(p,q=20):
def calc(x): p=p*q
global num q=p-q
if x > 200: print(p,q,sep='#',end=' ')
num *=2 return p
else:
num //= 2 p=10
return num/2 q=5
num = 1000 p=func1(p,q)
result = calc(num) print(p,q,sep='#',end=' ')
print (num,":",result) q=func1(q)
Output : 2000 : 1000.0 print(p,q,sep='#',end=' ')
Output : 50#45 50#5 100#80 50#100
Assessment
Give the output of the following Give the output of the following
x=5 def game(x,y=10):
y = 100 global a
def func(): a+=x+2
global x x+=20//y+5
y=x*2 y*=a%3
x = y + 12 print(a,x,y,sep=":")
print("x = ",x,"y = ",y) return x
return x + y a=5
print("x = ",x,"y = ",y) b,c=a+2,a*2
x += func() b=game(b)
print("x = ",x,"y = ",y) c=game(b,c)
print(a,b,c,sep=':')
Output : x = 5 y = 100
x = 22 y = 10 Output : 14:14:20
x = 37 y = 100 30:21:0
30:14:21
Assessment
Give the output of the following Give the output of the following
def calculate(a,b = 4): def game(x,y=10):
r =1 global a
for i in range(1,b + 1): a+=x+2
if b % i == 0: x+=20//y+5
r += a ** i y*=a%3
else: print(a,x,y,sep=":")
r -= a * i return x
print(r,end = '#') a=5
calculate(3) b,c=a+2,a*2
print() b=game(b)
calculate(3,2) c=game(b,c)
print(a,b,c,sep=':')
Output : 85# Output : 14:14:20
13# 30:21:0
30:14:21
Assessment
Give the output of the following Give the output of the following
def add(k): X = 50
s=0 def Alpha(num1):
for i in range(1,k+1): global X
if k % i == 0: num1 += X
X += 20
s += i num1 = Beta(num1)
return s return num1
def calc(num): def Beta(num1):
for i in range(num,0,-3): global X
num1 += X
if i%2!=0: X += 10
a=add(i) num1 = Gamma(num1)
return a+1,2*a+1,3*a+1 return num1
n=8 def Gamma(num1):
X = 200
p,q,r=calc(n) num1 += X
print(p,q,r) return num1
num = 100
Output : 7 13 19 num = Alpha(num)
print("Result -",num,x)
Output : Result - 420 80
Assessment
Give the output of the following Give the output of the following
def add(k): X = 50
s=0 def Alpha(num1):
for i in range(1,k+1): global X
if k % i == 0: num1 += X
X += 20
s += i num1 = Beta(num1)
return s return num1
def calc(num): def Beta(num1):
for i in range(num,0,-3): global X
num1 += X
if i%2!=0: X += 10
a=add(i) num1 = Gamma(num1)
return a+1,2*a+1,3*a+1 return num1
n=8 def Gamma(num1):
X = 200
p,q,r=calc(n) num1 += X
print(p,q,r) return num1
num = 100
Output : 7 13 19 num = Alpha(num)
print("Result -",num,x)
Output : Result - 420 80
global keyword
• A global object can also be created inside a UDF using global keyword
• To create a global object inside UDF, the object is declared with global
before it
Example : Creation of Global Object Inside a UDF
Program : def checknum():
global num #Global object created
num = int(input("Enter A number -"))
if num%2 == 0:
num*=2
else:
num//=2
checknum() # call statement to checknum()
print("changed num -",num) #Global num accessed outside UDF
• The global object num is created when checknum() is called
• Any attempt to access the object num before the function call statement of
checknum() will result Name Error.
Local Object with Same name as Global object

• In a Python program a local object can be created inside a UDF with


the same name as existing global object.
• When a Local object is created with the same name as the global
object, then the existing global object remains hidden inside the
UDF that declares the local object.
• The function having a local object with the same name as a global
object cannot access the global object directly.
• A global object remains global for a UDF, till it is not recreated inside
the function.
Local Object with Same name as Global object
Example: Local Object with Same name as Global object
Program : def fun():
num =100 # Statement 2 - local num = 100
print("Value of num inside function -",num)
num=10 # statement 1 - global num = 10
fun()
print("Value of num ouside function -",num) #statement 3
Output : Value of num inside function - 100
Value of num ouside function – 10
• In statement 1, the global object num is created and assigned with the value
10.
• In statement 2, inside the UDF fun(), when the object num is assigned with the
value 100 a new local object is created and by that the global object num
becomes inaccessible inside fun()
• When control comes out of UDF, Python destroys the local object num. The
print statement given in statement 3 outside the UDF displays the value of
global object num.
Nested Function
• When a User Defined function is defined inside another User Defined
function, it is called a nested function.
• The function which is defined inside is called the inner function or
Nested function
• and the function which is enclosing the inner function is called the
outer function.
• As the inner function is enclosed inside the outer function, inner
function can only be executed, through the outer function i.e to
execute inner function, outer function has to be called.
• The inner / Nested functions can access/display all objects created
inside the outer function.
Nested Function
Example : To demonstrate Nested function
Program : def outer_fun():
a=12 #Local object a created
def inner_fun():
b = a +12 #inner_fun() using local object a of outer_fun()
print(a,b) #inner_fun() printing object a of outer_fun()
inner_fun() called inside outer_fun()
outer_fun () #outer_fun() called in __main()__
• The outer_fun() is the outer function which is enclosing the inner function
inner_fun().
• The value of local object a, created inside outer_fun(), is used inside
inner_fun() to assign object b.
• when outer_fun() is called from main() segment, the local Object a is
created.
• The function call statement given inside the outer_fun() transfers the control
to the inner_fun().
• Inside the inner_fun() object b is created and assigned with the value 24
(a+12).
Nested Function
• In Python, the local objects created inside outer function are called
as Non-Local objects inside the inner functions.
• The non-local objects are by default read-only inside the nested
function i.e their values cannot be changed inside the inner
function.
• When any assignment statement is given inside the inner function
to change the value of local object of outer function,
• the assignment statement will create a local object in the scope
of inner function with the same name.
• The object created in outer function will remain hidden inside
inner function.
• The assignment will be applicable to the local object of inner
function without affecting the object of outer function.
• The object created inside inner function will be destroyed when
control leaves the inner function.
Nested Function
Example : local object of outer function inside the inner function
Program : def outer_fun():
#a = 12 # st 1 - Local object a is created inside outer_fun()
def inner_fun():
#a =100 # st 2- a is created inside inner_fun()
b = a +12
print("Value of b inside inner function - ",b)
print("Value of a inside inner function - ",a)
inner_fun() #inner_fun() called
print("Value of a outside inner function - ",a) #st 3
a=100
outer_fun() #Outer_fun() called
Output : Value of b inside inner function - 112
Value of a inside inner function - 100
Value of a outside inner function - 12
• When a is assigned to 100 inside inner_fun(), Python creates a local object in the
scope of inner_fun() which is destroyed when control leaves the inner_fun().
• The print statement given outside of inner_fun() (in st 3) displays the value of
local variable created inside the outer_fun() (i.e 12)
Nested Function
In order to modify the local objects created inside the outer function by using
assignment statement in the inner function, the nonlocal key word is used before
the object.

Example : To demonstrate nonlocal


Program : def f1():
a =12
def f2():
nonlocal a # a is declared as nonlocal
b = a +12 #value of b is assigned to 24
print(a,b) # will display12 24
a =100 # Value of nonlocal object a changed to 100
f2()
print("a = ",a) #will display 100
f1()
Nested Function
Example : Write a user defined function inprad() to input radius of a
circle and define a nested function calc() inside inprad() to
calculate and display diameter, area and perimeter of the
circle.
Program : def inprad():
r = float(input("Enter radius -"))
def calc():
d=2*r
ar = 3.14 * r ** 2
p = 2 * 3.14 * r
print("\nDiameter -",d)
print("Area – ",ar)
print("Perimeter – ",p)
calc() # call to inner function calc() inside inprad()
inprad() # call to outer function inprad()
Namespace in Python

• A name in Python refers to the names given to object or a Function/


method.
• A namespace in Python is an approach to define the scope of an
object .
• The Name refers to the name of an unique identifier and Space
implies to it’s scope i.e the location from where a statement is
trying to access it.

In a Python program, there are four types of namespaces:


• Built-In
• Global
• Enclosing
• Local
Namespace in Python
Built-in Namespace
• The Python interpreter creates the built-in namespace when it starts
up.
• Built-in namespace remains in existence until the Python interpreter
terminates.
• The built-in namespace contains the names of Python’s built-in
objects/methods/functions like id(), type(), print(), input() etc.
• These names existing in Built in namespace are available at all times
when Python interpreter is running.
Global Namespace
• The Global namespace contains all names defined at the level of the
main (top level segment) program.
• Python creates the global namespace when the main program body
starts, and it remains in existence until the interpreter terminates.
• The interpreter also creates a global namespace for any module that
the program loads with the import statement.
Namespace in Python
Local Namespace
• The Local namespace includes all local objects names created inside
a function.
• This namespace is created when a function is called, and it only lasts
until the function returns.

Enclosed Namespace
• When a function is defined inside a function (nested function), it
creates an enclosed namespace.
• The lifetime of objects created inside Enclosed namespace is same
as the local namespace.
• names created inside the inner functions will be destroyed when
control comes out of inner function.
Namespace in Python –LEGB Rule

• Whenever any identifier is used in a Python program, Python searches


through different scope levels (or namespaces) to determine whether
the name exists or not
• The LEGB-rule defines the rules following which Python searches for a
particular object/function. The LEGB rule is named after different
scopes of Python.
• The LEGB-rule stands for :
Local -> Enclosing -> Global -> Built-in,
where the arrows should denote the direction of the namespace-
hierarchy search order.
Namespace in Python –LEGB Rule
In LEGB rule
• The local refers to all objects that are defined inside a function. In
a nested function, Local refers to all objects created inside the
inner/nested function
• Enclosing refers to all names that exists only in outer function.
• Global refers to the names(variables, functions, objects and so
on) declared at the highest level in your program (__main__
segment)
• Built-in are special names that that are loaded whenever a
program is executed. This contains names such as keywords,,
functions and other attributes that are built into Python.
Namespace in Python –LEGB Rule

In a Python program, whenever a name is used


- Python interpreter will first search the local namespace i.e inside
the inner function.
- if the name cannot be found in the local namespaces, the
namespaces of the enclosing scope are being searched next i.e
in the outer function.
- If the search in the enclosing scope is unsuccessful, too, Python
moves on to the global namespace,
- and eventually, it will search the built-in namespace. If a name
cannot found in any of the namespaces, a NameError will is
raised.
Assessment
Consider the function with following header :
def calvolume(pi, rad=5, h=10)
Find out which of the following function call statements are valid/invalid.
Justify your answer based on the different methods of passing parameters

a. calvolume(3.14)
e. calvolume()
Answer : Correct Answer : Incorrect
b. calvolume(h=8,pi=3,rad=6)
f. calvolume(h=3,r1)
Answer : Correct (named argument) Answer : Incorrect
c. calvolume(3.14,rad=3) g. calvolume(h=12,pi=3)
Answer : Correct (mixed Argument) Answer : Correct
d. calvolume(r1,pi=3) h. calvolume(h=20)
Answer : Incorrect Answer : Incorrect
Assessment
Q Give suitable terms for the following descriptions based on the different
methods of passing parameters .

a. A name inside the parenthesis of function a. Parameter


header that can receive value b. Local object
b. An object created inside function body c. Global object
c. An object defined outside all function definitions d. Named argument
e. Default value
d. A value assigned to an argument in function call
f. Argument
statement
e. A value assigned to a parameter in function
header statement
f. A value passed by the function call statement
Assessment
Q The following code is given to calculate product of all digits of
a number. But it is not doing so? Justify your answer. Also what
will be the outputs at line4 and line5,after suitable
corrections?

def change(n):
while n>0: #line1
prod*=n%10 #line2 To get the desired result
prod = 1
n//=10 #line3 Output at line4 = 36
print(prod) #line4 Output at line5 = 1

prod=1
change(623)
print(prod) #line5


Assessment
Q Give the output of the following code. Also explain the statement global
num

num=100
def calc(x):
global num Output
if x>2: 1:1
num=1
else:
num=2
return num%2
num= 1000
result=calc(num)
print (num,”:”,result)

You might also like