Functions
Functions
Reusable block of code that performs a specific task. For example: len(),
print(), min(), max(), sorted () , type() etc.
Types of Functions
Name the function and specify what to do when the function is called. Python
interpreter ignores the function definition until the function is called.
Calling a function:
Calling the function using the function name performs the specified actions
with the indicated parameters
Function Definition in Python
In Python, a function is defined using the def keyword
● Arguments: Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma. Eg: add(a,b,c)
● Parameters: Parameters are variables specified in function definitions
to receive values from arguments passed during function calls.
Eg: def add(e,f,g) :
In Python, the scope of a variable refers to the region of the program where
the variable is accessible. The scope determines where a variable is
created, modified, and used.
Global Scope:
Local Scope:
Local variables are created when the function is called and destroyed when
the function returns.
Points to be noted:
● When the local variable and global variable have different names: the
global variable can be accessed inside the function
● When local and global variables have the same name: priority is given
to the local copy of the variable
Here's the basic syntax for using the global keyword: For example:
Example 1:
Example 2
Example 3
Example 4
Passing list as an argument to the function:
Please note that when a list is passed as an argument, the original copy
of the list is passed to the function i.e. if any change is made at any
index in the list inside the function, it is reflected in the original list.
That is because a list is a mutable datatype and in Python, when you
pass a list as an argument to a function, you are actually passing a
reference to the list rather than a copy of the list. This means that the
function parameter will point to the same memory location as the
original list. As a result, any changes made to the list within the function
will be reflected in the original list outside the function.
Default Arguments:
● Default arguments are used when a function is called with fewer
arguments than there are parameters.
● The default values are specified in the function definition.
● If a value is not provided for a parameter during the function call, the
default value is used.
● Default parameters are always specified at the end in the function
definition.
G – global environment
B- built in environment
If you want to use a value of already created global variable inside a local function
without modifying it, then simply use it.
But if you want to assign some value to the global variable without creating any
local variable, then use global keyword
Changes if any in mutable types are reflected in caller function if the name is not
assigned to a different variable or datatype.
The primary difference is that list concatenation creates an entirely new list object by
combining two sequences, while the append() method modifies the existing list in-place by
adding a single element to its end.
The core difference is that the + operator creates a brand-new list object in memory, while
the += operator modifies the existing list in-place
Default argument values are evaluated only once, when the function is defined, not each
time it is called.
FUNCTIONS – WORKSHEET – 1
1. What is the default value of a function that does not return any value.
a) None b) int c)double d) null
2. Which of the following items are present in the function header?
a) Function name only b) parameter List
c) Both function name and parameter list only d) Return value.
3. Which of the following keyword marks the beginning of the function block.
a) func b) define c) def d) function
4. Pick one of the following statements to correctly complete the function body in the given snippet:
def f (number):
#missing function body
print(f(5))
a) return “number” b) print(number) c) print(“number”) d) return number
5. Which of the following function header is correct.
22. If a function is returning multiple values, by default it returns in the form of ________
23. The parameter used in the function call statement are called _________ or ____________
24. The parameters used in the function Header are called________________ or ___________
25. _______are the named arguments with associated values being passed in the function call statement.
FUNCTIONS – WORKSHEET – 2 change()
Question 1 x=10
x=5 print(x,y,sep="*")
global x v=25
print(x,end=”@”) v=50
multiply() print(v,end=ch)
x=10 print(v,end="*")
print(x,end=”!”) fun("!")
Question 2: print(v)
p=1 Question 7:
global p Q=P-Q
q=5 print(P,”@”,Q)
p=p+q return P
return p R=200
change() S=100
print(p,q) print(R,”@”,S)
Question 3: S=call(S)
x=25 print(R,”@”,S)
x=x+5 P=P+Q
print(x) Q=P-Q
print(x) print(P,”#”,Q)
change() return P
Question 4: R=150
x=25 S=100
x=x+5 print(R,”#”,S)
print(x) S=change(S)
print(x) Question 9:
Question 5: x="Hello"
y=x inner()
print(x,y,end="-") return x
y=10 print(outer())
Question 9: return(ch)
def makenew(mystr): Question 12:
newstr="" def fun(str1):
count=0 n=len(str1)
for i in mystr: str2=''
if count%2!=0: for i in range(0,n):
newstr=newstr+str(count) if str1[i]>="A" and str1[i]<="M":
else: str2=str2+str1[i+1]
if [Link](): elif str1[i]>="0" and str1[i]<="9":
newstr=newstr+[Link]() str2=str2+str1[i-1]
else: else:
newstr=newstr+i str2=str2+"*"
count+=1 print(str2)
newstr=newstr+mystr[:1] fun("EXAM2025")
print(newstr) Question 13:
makenew("sTUdeNT") def change(P,Q=30):
Question 10: P=P+Q
def makenew(mystr): Q=P-Q
newstr="" print(P,"#",Q)
count=0 return(P)
for i in mystr: R=150
if count%2!=0: S=100
newstr=newstr+str(count) R=change(R,S)
else: print(R,"#",S)
if [Link](): S=change(S)
newstr=newstr+[Link]() print(R,"#",S)
else: S=change(R)
newstr=newstr+i print(R,"#",S)
count+=1 Question 14:
print(newstr) The code provided below is intended to remove
the first and last characters of a given string and
makenew("No@1") return the resulting string. However, there are
Question 11: The function given below is written syntax and logical errors in the code. Rewrite it
to accept a string s as a parameter and return the after removing all the errors. Also, underline all
number of vowels appearing in the string. The the corrections made.
code has certain errors. Observe the code define remove_first_last(str):
carefully and rewrite it after removing all the if len(str) < 2:
logical and syntax errors. Underline all the return str
corrections made. new_str = str[1:-2]
Def CountVowels(s): return new_str
result = remove_first_last("Hello")
C=0
Print("Resulting string: " result)
for ch in range(s):
if ‘aeiouAEIOU’ in ch:
c+=1
FUNCTIONS – WORKSHEET – 3
1. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The
function returns another list named ‘indexList’ that stores the indices of all Non - Zero Elements of L.
2. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as argument to
the function. The function returns another list named ‘indexList’ that stores the indices of all four
lettered word of L. For example :If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
3. Write a function modilst(L) that accepts a list of numbers as argument and increases the value of the
elements by 10 if the elements are divisible by [Link] write a proper call statement for the function.
For example:If list L contains [3,5,10,12,15]
4. Write a function countNow (DAYS) in Python, that takes the dictionary, DAYS as an argument and
displays the names (in lowercase) of the days whose names are longer than 7 characters. For
example, Consider the following dictionary
DAYS={1:"MONDAY",2:"TUESDAY",3:"WEDNESDAY",4:"THURSDAY",5:"FRIDAY",6:” ,
“SATURDAY”,7:”SUNDAY”}
5. The code provided below is intended to swap the first and last elements of a given tuple. However,
there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the
corrections made.
def swap_first_last(tup)
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
return new_tup
result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)
6. The code provided below is intended to input a positive integer from the user and display the total
number of its factors. However, there are syntax and logical errors in the code. Rewrite the code
after removing all the errors. Underline all the corrections made.
n=int(input("Enter a positive integer:")
c=0
for i in range(n+1):
if n%i=0:
c+=1
print(c)
7. The code given below accepts N as an integer argument and returns the sum of all integers from 1 to
N. Observe the following code carefully and rewrite it after removing all syntax and logical errors.
Underline all the corrections made.
def Sum(N)
for I in range(N):
S=S+I
return S
print(Sum(10)
8. Write a Python function update_score() that accepts a dictionary named scores, a player name and a
new score. If the player name already present in dictionary, update the score, otherwise, display the
message "Player not found".
9. Write a function remove_duplicates() in Python that accepts a list L and returns a new list containing
only the unique elements from L, after removing the duplicates.
10. The code provided below is intended to swap the first and last elements of a given tuple. However,
there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the
corrections made.
def swap_first_last(tup)
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
return new_tup
result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)
11. The code provided below is intended to input a positive integer from the user and display the total
number of its factors. However, there are syntax and logical errors in the code. Rewrite the code
after removing all the errors. Underline all the corrections made.
n=int(input("Enter a positive integer:")
c=0
for i in range(n+1):
if n%i=0:
c+=1
print(c)
12. Write a user defined function in Python named showGrades(S) which takes the dictionary S as an
argument. The dictionary, S contains Name:[Eng,Math,Science] as key:value pairs. The function
displays the corresponding grade obtained by the students according to the following grade rules.
Average of Eng,Math,Science Grade
>=90 A
<90 but >=60 B
<60 C
For example : Consider the following dictionary
S={“AMIT”:[92,86,64], “NAGMA”:[65,42,43], “DAVID”:[92,90,88]}
The output should be :
AMIT – B
NAGMA – C
DAVID – A
13. Write a user defined function in python named Puzzle(W,N) which take the argument W as an English
word and N as an integer and returns the string where every Nth alphabet of the word W is replaced
with an underscore(“_”)
For example: if W contains the word “TELEVISION” and N is 3, then the function should return the
string “TE_EV_SI_N”. Likewise for the word “TELEVISION”, IF n IS 4, then the function should return
“TEL_VIS_ON”.
FUNCTIONS – OUTPUT BASED QUESTIONS
1. def Findoutput():
L = "First PreBoard"
X = ""
count = 1
for i in L:
if i in ['a', 'e', 'i', 'o', 'u']:
X = X + [Link]()
else:
if count % 2 != 0:
X = X + str(len(L[:count]))
else:
X = X + i
count = count + 1
print(X)
Findoutput()
2. tup = ('cold',)
n = 4
for i in range(int(n)):
if i % 2 == 0:
tup = (tup,'cold')
else:
if i > 1:
continue
tup = (tup , 'hot')
print(tup)
3. s = "welcome2kv"
n = len(s)
m = ""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m + s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m + s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '#'
print(m)
8. def display(s):
l = len(s)
m = ""
for i in range(0, l):
if s[i].isupper():
m = m + s[i].lower()
elif s[i].isalpha():
m = m + s[i].upper()
elif s[i].isdigit():
m = m + "$"
else:
m = m + "*"
print(m)
display("EXAM2026@[Link]")
9. def makenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count % 2 != 0:
newstr = newstr + str(count)
else:
if [Link]():
newstr = newstr + [Link]()
else:
newstr = newstr + i
count += 1
newstr = newstr + mystr[:1]
print("The new string is :", newstr)
makenew("WeLlFArE")
11. data=["L",20,"M",40,"N",60]
Times,add=0,0
alpha=""
for c in range(1,6,2):
times = times + c
alpha = alpha + data[c-1] + "@"
add = add + data[c]
print(times, add, alpha)
12. d1={'rno':25, 'name':'dipanshu'}
d2={'name':'himanshu', 'age':30, 'dept':'mechanical'}
[Link](d1)
print([Link]())
print(len(list([Link]())))
13. def foo(s1, s2): def SW (a, b):
l1 = [] if a > b:
l2 = [] print("changed",end="")
for x in s1: return b , a
[Link](x) else:
for x in s2: print("Not",end="")
[Link](x) return a , b
return l1, l2 L = [11, 22, 16, 50, 30]
a, b = foo("FUN", "DAY") for i in range(4, 0, -1):
print(a, b) print(SW(L[i], L[i-1]))
14. data = [2,4,2,1,2,1,3,3,4,4]
d = {}
for x in data:
if x in d:
d[x] = d[x] + 1
else:
d[x] = 1
print(d)
15. i. def change(m, n=10): ii) a = -30
global x def call(x):
x += m global a
n += x if a % 2 ==0:
m = n + x x+=a
print(m, n, x) else:
x = 20 x-=a
change(10) return x
change(20) x=20
print(call(35), end="#")
print(call(40), end="@")
16. str = "" What are the possible outputs ?
name = "9@Days" import random
for x in name: M=[5,10,15,20,25,30]
if x in "aeiou": for I in range(1,3):
str += [Link]() F=[Link](2,5)-1
elif not [Link](): S=[Link](3,6)-2
str += "**" T=[Link](1,4)
elif [Link](): print(M[F],M[S],M[T],sep="#")
pass i) 10#25#15 ii) 5#25#25
else: 20#25#25 25#20#15
str += [Link]() iii) 30#20#20 iv) 10#15#25
print(str) 20#25+25 15#20#10#
32. What are the possible outputs for (a) and (b) ?
a) import random
AR = ["MON", "TUE", "WED", "THU", "FRI", "SAT"]
X = [Link](0, 4)
for I in range(1, X+1):
print(AR[I] + "#", end="")
36. count = 0
while(True):
if count % 3 == 0:
print(count, end = " ")
if(count > 15):
break;
count += 1
37. def encrypt(s):
k = len(s)
m = ""
for i in range(0, k):
if s[i].isupper():
m = m + str(i)
elif s[i].islower():
m = m + s[i].upper()
else:
m = m + '*'
print(m)
encrypt(“MouNT@TowN”)
38. def fun(s):
k = len(s)
m = " "
for i in range(0, k):
if s[i].isupper():
m = m + s[i].lower()
elif s[i].islower():
m = m + s[i].upper()
elif s[i].isdigit():
m = m + "O"
else:
m = m + '#'
print(m)
fun('CBSE@12@Exam')
39. L1 = [100, 900, 300, 400, 500] p,q=8,[8]
START , SUM = 1 , 0 def sum(r, s=5):
for C in range(START, 4): p = r + s
SUM = SUM + L1[C] q = [r, s]
print(C, ":", SUM) print(p, q, sep='@')
SUM = SUM + L1[0] * 10 sum(3, 4)
print(SUM) print(p, q, sep='@')
40. def replaceV(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = "Hello how are you"
st1 = replaceV(st)
print("The original String is:", st)
print("The modified String is:", st1)
a. Delhi#Mumbai#Chennai#Kolkata#
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai
54. LST=[5,10,15,20,25,30,35,40,45,50,60,70]
a = randint(3,8) (i) 20#25#25#
b = randint(4,9) (ii) 30#40#70#
c = randint(6,11) (iii) 15#60#70#
print(LST*a+, “#”,LST*b+, “#”,LST*c+, “#”) (iv) 35#40#60#
55. hello = {empname: "Ishan", address: ”New Delhi”, salary: 10000}
hello[salary] = 15000
hello[address] = "Delhi"
print([Link]())
print(len([Link]())))
print(tuple([Link]()))
56. Original = [10, 20, 30, 40, 50]
Result = {}
while len(Original) > 0:
Val = [Link]()
if Val % 20 == 0:
Result[Val] = "Double"
else:
Result[Val] = "Triple"
for k, v in [Link]():
print(k, v, sep=":")
57. def fun1():
x = 100
def fun2():
x = 200
print("x in func()2", x)
print("Before calling fun2: " + str(x))
fun2()
print("After calling fun2: " + str(x))
global x
x = 50
fun1()
print("x in main: " + str(x))
58. def fun1():
x = 100
def fun2():
nonlocal x
x = 200
print("x in func()2:", x)
print("Before calling fun2:", x)
fun2()
print("After calling fun2:", x)
x = 50
fun1()
print("x in main:", x)
59. s="GuDLuck4Xam2026"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)
b. def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))