36 questions from CBSE board, sample and compartment papers (2024–2027), 1 to 3 marks, each with a model answer. Questions on defining and calling functions, positional and default parameters, return values, local and global variables (the global keyword), possible outputs with the random module, finding and correcting errors in given code, and writing short functions. Programming answers open in the Python Lab.
Working with Python Function· 1 Mark· Q1· 2024 Board Paper
State True or False:
While defining a function in Python, the positional parameters in the function header must always be written after the default parameters.
Model answer
False
Explanation: In Python, positional parameters must always appear before default parameters in the function header. Placing a non-default argument after a default argument raises a SyntaxError.
Working with Python Function· 1 Mark· Q4· 2024 Board Paper Python
What possible output from the given options is expected to be displayed when the following Python code is executed?
import random
Signal = ['RED', 'YELLOW', 'GREEN']
for K in range(2, 0, -1):
R = random.randrange(K)
print(Signal[R], end = '#')
(A)YELLOW # RED #
(B)RED # GREEN #
(C)GREEN # RED #
(D)YELLOW # GREEN #
Model answer
(a) YELLOW # RED #
Explanation: When K=2, randrange(2) gives 0 ('RED') or 1 ('YELLOW'). When K=1, randrange(1) can only give 0 ('RED'). Thus valid outputs are 'RED # RED #' or 'YELLOW # RED #'. Among the options, (a) is correct.
import random
Signal = ['RED', 'YELLOW', 'GREEN']
# Simulating output for K=2 (R=1) and K=1 (R=0)
print(Signal[1], end='#')
print(Signal[0], end='#')
Working with Python Function· 1 Mark· Q12· 2024 Board Paper Python
Observe the given Python code carefully:
a=20
def convert(a):
b=20
a=a+b
convert(10)
print(a)
Select the correct output from the given options:
(A)10
(B)20
(C)30
(D)Error
Model answer
(b) 20
Explanation: Inside convert(), parameter 'a' is local to the function. Changes to it do not modify the global variable 'a'. print(a) prints 20.
Working with Python Function· 2 Marks· Q20· 2024 Board Paper
The code given below accepts five numbers and displays whether they are even or odd:
Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
def EvenOdd()
for i in range(5):
num=int(input("Enter a number")
if num/2==0:
print("Even")
else:
print("Odd")
EvenOdd()
Model answer
def EvenOdd():
for i in range(5):
num = int(input("Enter a number"))
if num % 2 == 0:
print("Even")
else:
print("Odd")
EvenOdd()
Corrections made:
1. Added colon (:) after def EvenOdd()
2. Added missing closing parenthesis: int(input("Enter a number"))
3. Used modulus operator (%) instead of division (/): num % 2 == 0
4. Indented print("Odd") inside the else block
def EvenOdd():
for i in range(5):
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Working with Python Function· 2 Marks· Q21· 2024 Board Paper Python
(A) Write a user defined function in Python named showGrades(S) which takes the dictionary S as an argument. S contains Name: [Eng, Math, Science] as key:value pairs. The function displays the corresponding grade obtained by the students according to the following grading rules:
Average >= 90: Grade A
< 90 but >= 60: Grade B
< 60: Grade C
For example: S={"AMIT": [92,86,64], "NAGMA": [65,42,43], "DAVID": [92,90,88]}
Output should be:
AMIT - B
NAGMA - C
DAVID - A
OR
(B) Write a user defined function in Python named Puzzle(W,N) which takes 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 "TELEVISION" and N is 3, then the function should return "TE_EV_SI_N". If N is 4, then return "TEL_VIS_ON".
Model answer
(A)
def showGrades(S):
for name, marks in S.items():
avg = sum(marks) / len(marks)
if avg >= 90:
grade = 'A'
elif avg >= 60:
grade = 'B'
else:
grade = 'C'
print(name, "-", grade)
OR
(B)
def Puzzle(W, N):
res = ""
for i in range(len(W)):
if (i + 1) % N == 0:
res += "_"
else:
res += W[i]
return res
# Part A:
def showGrades(S):
for name, marks in S.items():
avg = sum(marks) / len(marks)
if avg >= 90:
grade = 'A'
elif avg >= 60:
grade = 'B'
else:
grade = 'C'
print(name, "-", grade)
S = {"AMIT": [92, 86, 64], "NAGMA": [65, 42, 43], "DAVID": [92, 90, 88]}
showGrades(S)
# Part B:
def Puzzle(W, N):
res = ""
for i in range(len(W)):
res += "_" if (i + 1) % N == 0 else W[i]
return res
print("Puzzle test:", Puzzle("TELEVISION", 3))
Working with Python Function· 2 Marks· Q25· 2024 Board Paper Python
Predict the output of the following code:
def callon(b=20,a=10):
b=b+a
a=b-a
print(b,"#",a)
return b
x=100
y=200
x=callon(x,y)
print(x,"@",y)
y=callon(y)
print(x,"@",y)
Model answer
300 # 100
300 @ 200
210 # 200
300 @ 210
Explanation: 1. callon(100, 200): b = 300, a = 100 -> prints '300 # 100', returns 300 to x.
2. print(x, '@', y) prints '300 @ 200'.
3. callon(200): b=200, a=10 -> b=210, a=200 -> prints '210 # 200', returns 210 to y.
4. print(x, '@', y) prints '300 @ 210'.
def callon(b=20, a=10):
b = b + a
a = b - a
print(b, "#", a)
return b
x = 100
y = 200
x = callon(x, y)
print(x, "@", y)
y = callon(y)
print(x, "@", y)
Working with Python Function· 1 Mark· Q10· 2025 Board Paper Python
Consider the statements given below and then choose the correct output from the given options:
def Change(N):
N=N+10
print(N,end='$$')
N=15
Change(N)
print(N)
(A)25$$15
(B)15$$25
(C)25$$25
(D)2525$$
Model answer
25$$15
Explanation: Inside the function, N becomes 25. Outside, N remains 15 (immutable integer).
def Change(N):
N = N + 10
print(N, end='$$')
N = 15
Change(N)
print(N)
Working with Python Function· 2 Marks· Q22· 2025 Board Paper Python
What does the return statement do in a function? Explain with the help of an example.
Model answer
The return statement ends the execution of a function and returns a value to the caller.
def multiply(a, b):
return a * b
# Calling the function
result = multiply(5, 4)
print(f'The result is: {result}')
Working with Python Function· 2 Marks· Q25· 2025 Board Paper
What possible output from the given options is expected to be displayed when the following code is executed?
import random
Cards=["Heart","Spade","Club","Diamond"]
for i in range(2):
print(Cards[random.randint(1,i+2)],end="#")
(A)Spade#Diamond#
(B)Spade#Heart#
(C)Diamond#Club#
(D)Heart#Spade#
Model answer
Spade#Diamond#
Explanation: random.randint(1, i+2) logic: Loop 1 (i=0): randint(1,2) -> index 1 or 2 (Spade or Club). Loop 2 (i=1): randint(1,3) -> index 1, 2, or 3. Option (A) fits
import random
Cards = ['Heart', 'Spade', 'Club', 'Diamond']
for i in range(2):
print(Cards[random.randint(1, i + 2)], end='#')
Working with Python Function· 2 Marks· Q26· 2025 Board Paper Python
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)
def Sum(N):
S = 0
for I in range(1, N + 1):
S = S + I
return S
print(Sum(10))
Explanation: Corrections: colon added after def Sum(N); S = 0 added before the loop; range(N) changed to range(1, N + 1) so that 1 to N are added; closing bracket added in print(Sum(10)).
Working with Python Function· 1 Mark· Q9· 2026 Board Paper Python
What will be the output of the following code?
def f1(a, b=1):
print(a+b, end='-')
c = f1(1, 2)
print(c, sep='*')
(A)3-2
(B)3-2*
(C)3-None
(D)3*None-
Model answer
3-None
Explanation: f1(1,2) prints '3-' and returns None (as there is no return statement). Then 'c' is assigned None. The subsequent print statement prints None. Resulting combined output: '3-None'.
Working with Python Function· 2 Marks· Q22· 2026 Board Paper Python
What is the difference between default parameters and positional parameters in Python? Also give an example of a function header which uses both.
Model answer
Default parameters have pre-assigned values and can be skipped during a call. Positional parameters require values passed in exact order. Default parameters must always follow positional parameters.
# Example of a function header using both
def calculate_discount(price, discount=10):
# price is positional, discount is default
return price - (price * discount / 100)
print("Price with default:", calculate_discount(1000))
print("Price with specific discount:", calculate_discount(1000, 20))
Working with Python Function· 2 Marks· Q25· 2026 Board Paper Python
What possible output(s) from the given options will NOT be displayed when the following code is executed? Also, mention, for how many iterations the for loop in the given code will run?
import random
a = [1, 2, 3, 4, 5, 6]
for i in range(4):
j = random.randrange(i, 5)
print(a[j], end='-')
print()
Options:
(A) 3-4-5-4-
(B) 2-2-4-5-
(C) 4-3-3-5-
(D) 5-1-2-4-
Model answer
Option (D) 5-1-2-4- will NOT be displayed.
The for loop will run for 4 iterations.
Explanation: random.randrange(i, 5) picks from index i to 4.
i=0: picks index 0..4 (Values: 1,2,3,4,5)
i=1: picks index 1..4 (Values: 2,3,4,5) - thus '1' is impossible here.
i=2: picks index 2..4 (Values: 3,4,5)
i=3: picks index 3..4 (Values: 4,5)
Option D tries to print '1' on the second iteration, which is impossible. So D is incorrect.
import random
a = [1, 2, 3, 4, 5, 6]
for i in range(4):
j = random.randrange(i, 5)
print(a[j], end='-')
Working with Python Function· 2 Marks· Q26· 2026 Board Paper Python
The function given below is written to accept a string s as a parameter and return the number of vowels appearing in the string. The code has certain errors. Rewrite it after removing all the logical and syntax errors.
def CountVowels(s):
c = 0
for ch in range(s):
if 'aeiouAEIOU' in ch:
c =+ 1
return (ch)
Model answer
Corrections made: changed 'range(s)' to 's', flipped the condition to 'ch in aeiouAEIOU', corrected '=+1' to '+=1', and changed 'return(ch)' to 'return c'.
def CountVowels(s):
c = 0
for ch in s: # Correction 1
if ch in 'aeiouAEIOU': # Correction 2
c += 1 # Correction 3
return c # Correction 4
print("Vowels count:", CountVowels("Hello World"))
Working with Python Function· 1 Mark· Q12· 2025 Compartment Paper Python
What will be the output of the following code segment?
a = 5
def func_1(b=10):
global a
a = b - 10
b += a
print(a, b)
func_1(a)
(A)0 5
(B)5 0
(C)0 -5
(D)-5 0
Model answer
-5 0
Explanation: func_1 is called with b=5 (the global 'a'). global a assigns the function scope to global 'a'. a = 5 - 10 = -5. b = 5 + (-5) = 0. Output is -5 0.
a = 5
def func_1(b=10):
global a
a = b - 10
b += a
print(a, b)
func_1(a)
Working with Python Function· 2 Marks· Q25· 2025 Compartment Paper Python
Identify the correct possible output(s) of the following code segment. Also write the minimum and the maximum possible values of the variable b.
import random
s="War and Peace"
a = len(s)//2
for i in range(4):
b = random.randrange(i, a)
print(s[b], end='+')
(A) n+P+d+a+
(B) W+r+n+n+
(C) e+r+W+a+
(D) a+P+e+r+
Model answer
Correct Output: (B) W+r+n+n+
Minimum possible value of b is 0. Maximum possible value of b is 5.
Explanation: Length of 'War and Peace' is 13. a = 13 // 2 = 6.
Loop runs for i = 0, 1, 2, 3.
random.randrange(i, 6) generates integers between i and 5 (inclusive). Therefore, b cannot exceed 5. Option B characters map correctly within the allowed bounds.
import random
s="War and Peace"
a = len(s)//2
for i in range(4):
b = random.randrange(i, a)
print(s[b], end='+')
Working with Python Function· 1 Mark· Q10· 2024 Sample Paper Python
What possible outputs(s) will be obtained when the following code is executed?
import random
myNumber=random.randint(0,3)
COLOR=["YELLOW","WHITE","BLACK","RED"]
for I in range(1,myNumber):
print(COLOR[I],end="*")
print()
(A)a.
RED*
WHITE*
BLACK*
(B)b.
WHITE*
BLACK*
(C)c.
WHITE* WHITE*
BLACK* BLACK*
(D)d.
YELLOW*
WHITE*WHITE*
BLACK* BLACK* BLACK*
Model answer
Option b
WHITE*
BLACK*
Explanation: When randint(0,3) generates 3, range(1,3) iterates over I = 1 and 2, printing COLOR[1] ('WHITE*') and COLOR[2] ('BLACK*').
import random
COLOR=["YELLOW","WHITE","BLACK","RED"]
for I in range(1,3):
print(COLOR[I],end="*")
print()
Working with Python Function· 1 Mark· Q12· 2024 Sample Paper Python
Consider the code given below:
b=100
def test(a):
# missing statement
b=b+a
print(a,b)
test(10)
print(b)
Which of the following statements should be given in the blank for #Missing Statement, if the output produced is 110?
(A)a. global a
(B)b. global b=100
(C)c. global b
(D)d. global a=100
Model answer
Option c
global b
Explanation: The 'global b' declaration informs Python that 'b' refers to the globally defined variable, allowing modification inside the function.
b=100
def test(a):
global b
b=b+a
print(a,b)
test(10)
print(b)
Working with Python Function· 1 Mark· Q18· 2024 Sample Paper
Assertion(A): Python Standard Library consists of various modules.
Reasoning(R): A function in a module is used to simplify the code and avoids repetition.
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
(A)(a) Both A and R are true and R is the correct explanation for A
(B)(b) Both A and R are true and R is not the correct explanation for A
(C)(c) A is True but R is False
(D)(d) A is false but R is True
Model answer
Option b
Both A and R are true but R is not the correct explanation for A
Explanation: Both statements are true facts about Python, but the reusability of functions in modules does not explain the composition of the standard library.
Working with Python Function· 2 Marks· Q20· 2024 Sample Paper Python
The code given below accepts a number as an argument and returns the reverse number. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
define revNumber(num) :
rev = 0
rem = 0
While num > 0:
rem ==num %10
rev = rev*10 + rem
num = num//10
return rev
print(revNumber(1234))
Model answer
def revNumber(num):
rev = 0
rem = 0
while num > 0:
rem = num % 10
rev = rev*10 + rem
num = num//10
return rev
print(revNumber(1234))
def revNumber(num):
rev = 0
rem = 0
while num > 0:
rem = num % 10
rev = rev*10 + rem
num = num//10
return rev
print(revNumber(1234))
Working with Python Function· 2 Marks· Q21· 2024 Sample Paper Python
Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an argument and displays the names (in uppercase)of the places whose names are longer than 5 characters.
For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be:
LONDON
NEW YORK
OR
Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3)
Model answer
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
def countNow(PLACES):
for place in PLACES.values():
if len(place)>5:
print(place.upper())
countNow(PLACES)
OR
def lenWords(STRING):
T=()
L=STRING.split()
for word in L:
length=len(word)
T=T+(length,)
return T
Note: Any other correct logic may be marked
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
def countNow(PLACES):
for place in PLACES.values():
if len(place)>5:
print(place.upper())
countNow(PLACES)
Working with Python Function· 2 Marks· Q25· 2024 Sample Paper Python
Predict the output of the following code:
def Changer(P,Q=10):
P=P/Q
Q=P%Q
return P
A=200
B=20
A=Changer(A,B)
print(A,B,sep='$')
B=Changer(B)
print(A,B,sep='$',end='###')
Working with Python Function· 1 Mark· Q12· 2025 Sample Paper Python
What will be the output of the following code?
c = 10
def add():
global c
c = c + 2
print(c,end='#')
add()
c=15
print(c,end='%')
(A)12%15#
(B)15#12%
(C)12#15%
(D)12%15#
Model answer
12#15%
Explanation: Global c becomes 12 inside function. Then c is set to 15 globally outside.
c=10
def add():
global c
c=c+2
print(c, end='#')
add()
c=15
print(c, end='%')
Working with Python Function· 1 Mark· Q20· 2025 Sample Paper
Assertion (A): Positional arguments in Python functions must be passed in the exact order in which they are defined in the function signature.
Reasoning (R): This is because Python functions automatically assign default values to positional arguments.
(A)Both A and R are True and R is the correct explanation for A
(B)Both A and R are True and R is not the correct explanation for A
(C)A is True but R is False
(D)A is False but R is True
Model answer
(C) A is True but R is False
Explanation: Positional arguments are matched by position, so A is true. Python does not give default values to positional arguments automatically, so R is false.
Working with Python Function· 2 Marks· Q25· 2025 Sample Paper
Identify the correct output(s) of the following code. Also write the minimum and the maximum possible values of the variable b.
import random
a="Wisdom"
b=random.randint(1,6)
for i in range(0,b,2):
print(a[i],end='#')
(A)W#
(B)W#i#
(C)W#s#
(D)W#i#s#
Model answer
(A) W# and (C) W#s#
Minimum value of b: 1, maximum value of b: 6
Explanation: b is 1 to 6. i takes 0, 2, 4 only, so the letters come from W, s, o: W# (b is 1 or 2), W#s# (b is 3 or 4), W#s#o# (b is 5 or 6).
Working with Python Function· 2 Marks· Q26· 2025 Sample Paper Python
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)
Explanation: Corrections: colon added after the def line; the if body indented; (tup[0]) changed to (tup[0],) so that it is a tuple; comma added in the print statement.
Working with Python Function· 1 Mark· Q1· 2026 Sample Paper
State if the following statement is True or False:
Using the statistics module, the output of the below statements will be 20:
import statistics
statistics.median([10, 20, 10, 30, 10, 20, 30])
Model answer
True
Explanation: The list sorted is [10, 10, 10, 20, 20, 30, 30]. The middle element (median) is 20.
Working with Python Function· 1 Mark· Q11· 2026 Sample Paper Python
What possible output is expected to be displayed on the screen at the time of execution of the Python program from the following code?
import random
L=[10,30,50,70]
Lower=random.randint(2,2)
Upper=random.randint(2,3)
for K in range(Lower, Upper+1):
print(L[K], end="@")
(A)50@70@
(B)90@
(C)10@30@50@
(D)10@30@50@70@
Model answer
50@70@
Explanation: Lower is always 2. Upper can be 2 or 3. If Upper=2, range(2,3) -> index 2 -> 50@. If Upper=3, range(2,4) -> indices 2,3 -> 50@70@.
import random
L = [10, 30, 50, 70]
# Mocking randint to show one possible outcome (Upper=3)
Lower = 2
Upper = 3
for K in range(Lower, Upper + 1):
print(L[K], end="@")
Working with Python Function· 1 Mark· Q12· 2026 Sample Paper Python
What will be the output of the following Python code?
i = 5
print(i,end='@@')
def add():
global i
i = i+7
print(i,end='##')
add()
print(i)
(A)5@@12##15
(B)5@@5##12
(C)5@@12##12
(D)12@@12##12
Model answer
5@@12##12
Explanation: First print 5@@. Function adds 7 to global i (becomes 12), prints 12##. Last print prints global i (12).
i = 5
print(i, end='@@')
def add():
global i
i = i + 7
print(i, end='##')
add()
print(i)
Working with Python Function· 2 Marks· Q23· 2026 Sample Paper Python
The code provided below is intended to remove the first and last characters of a given string and return the resulting string. However, there are syntax and logical errors in the code. Rewrite it after removing all the errors. Also, underline all the corrections made.
define remove_first_last(str):
if len(str) < 2:
return str
new_str = str[1:-2]
return new_str
result = remove_first_last("Hello")
Print("Resulting string: " result)
Model answer
Corrected code provided in solution.
def remove_first_last(str):
if len(str) < 2:
return str
new_str = str[1:-1] # Corrected slicing to remove last char
return new_str
result = remove_first_last("Hello")
print("Resulting string: ", result)
Working with Python Function· 2 Marks· Q25· 2026 Sample Paper Python
A. Write a function remove_element() in Python that accepts a list L and a number n. If the number n exists in the list, it should be removed. If it does not exist, print a message saying "Element not found".
OR
B. Write a Python function add_contact() that accepts a dictionary phone_book, a name, and a phone number. The function should add the name and phone number to the dictionary. If the name already exists, print "Contact already exists" instead of updating it.
def remove_element(L, n):
if n in L:
L.remove(n)
else:
print("Element not found")
# Test remove_element()
my_list = [10, 20, 30]
remove_element(my_list, 20)
print(my_list)
remove_element(my_list, 40)
def add_contact(phone_book, name, phone):
if name in phone_book:
print("Contact already exists")
else:
phone_book[name] = phone
# Test add_contact()
contacts = {"Rahul": "9876543210"}
add_contact(contacts, "Amit", "9123456789")
print(contacts)
add_contact(contacts, "Rahul", "9000000000")
Working with Python Function· 1 Mark· Q6· 2027 Sample Paper Python
What possible output is expected to be displayed on the screen at the time of execution of the Python program from the following code?
import random
games = {0: "Chess",1: "Scrabble",2: "Sudoku",3: "Tic-Tac-Toe",4: "Puzzle"
}
start_key = random.randint(1, 2)
end_key = random.randrange(3, 4)
for k in range(start_key, end_key + 1):
print(games[k], end="@@")
(A)Sudoku@@Tic-Tac-Toe@@Puzzle@@
(B)Scrabble@@Sudoku@@Tic-Tac-Toe@@
(C)Chess@@Scrabble@@Tic-Tac-Toe@@
(D)Scrabble@@Tic-Tac-Toe@@
Model answer
b) Scrabble@@Sudoku@@Tic-Tac-Toe@@
import random
games = {0: "Chess",1: "Scrabble",2: "Sudoku",3: "Tic-Tac-Toe",4: "Puzzle"
}
start_key = 1
end_key = 3
for k in range(start_key, end_key + 1):
print(games[k], end="@@")
Working with Python Function· 1 Mark· Q16· 2027 Sample Paper
What will be the output of the following Python code?
y = 8
def update():
y = y + 2
print(y)
update()
(A)10
(B)8
(C)Error
(D)None
Model answer
c) Error
Working with Python Function· 2 Marks· Q22· 2027 Sample Paper
A. Define global variable and local variable with a suitable example.
OR
B. Write the difference between the seek() and tell() methods in Python text file handling with a suitable example.
Model answer
A. Global variable: Defined outside a function; accessible anywhere in the program.
x = 10 # global
print(x)
Local variable: Defined inside a function; accessible only inside that function.
def demo():
y = 5 # local
print(y)
OR
B. tell(): Returns the current position of the file pointer in the file.
f = open("file.txt", "r")
print(f.tell()) # e.g.,0
seek(offset): Moves the file pointer to a specified position in the file.
f.seek(5) # moves pointer to 5th byte
Working with Python Function· 2 Marks· Q24· 2027 Sample Paper Python
A. Write a Python function capitalize_words(words) that takes a list of strings words and returns a new list with each word capitalize.
Example:
If the input is ["python", "computer", "science"]
The output should be ["Python", "Computer", "Science"].
OR
B. Write a Python function sum_positive(list1) that takes a list of numbers and prints the sum of all positive numbers in the list.
Example:
If the input is [10, -5, 20, -3, 7]
The output should be 37.
Model answer
A.
def capitalize_words(words): #words is a list of strings
result = [ ]
for w in words:
result.append(w.capitalize())
print(result)
OR
B.
def sum_positive(list1): #list1 is a list of numbers
total = 0
for num in list1:
if num > 0:
total += num
print(total)
def capitalize_words(words):
result = [ ]
for w in words:
result.append(w.capitalize())
print(result)
capitalize_words(["python", "computer", "science"])
Working with Python Function· 3 Marks· Q31· 2027 Sample Paper Python
A. Write a Python function avg_len( ) segment that adds up the lengths of all the words in a list and then prints the average (mean) length.
OR
B. Consider the tuple pairs = ((2,5),(4,2),(9,8),(12,10)). Write a Python function cnt_even( ) to count the number of pairs (a, b) where both a and b are even.
Model answer
A.
def avg_len(words):
total = 0
count = 0
for w in words:
total += len(w)
count += 1
return total / count
my_words = ["computer", "science", "python", "data"]
print("Average word length:", avg_len(my_words))
OR
B.
pairs = ((2,5), (4,2), (9,8), (12,10))
def cnt_even(t):
c = 0
for a, b in t:
if a % 2 == 0 and b % 2 == 0:
c += 1
return c
print("Number of even-even pairs:", cnt_even(pairs))
def avg_len(words):
total = 0
count = 0
for w in words:
total += len(w)
count += 1
return total / count
my_words = ["computer", "science", "python", "data"]
print("Average word length:", avg_len(my_words))