Python - User Defined Functions
Python - User Defined Functions
What is Function?
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
[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___________
The data items which are passed to the function to work on it are
referred as ___________.
Answer : Parameter
Examples Of Function Definition
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
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
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
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.
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__
Answer : c None
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.
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))
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
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
def checkpalin(str):
if str == str[::-1]:
return 1
else:
return 0
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)
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
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)
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
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
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)
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
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 .
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)