MauryaHub PYQ Practice

Programming in Python · End Term · Sep 2025 · FN

Programming in Python · End Term · Sep 2025 FN

← Course papers · Start practice / exam

Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.

18 / 18 published solutions

Question 2 MCQ · 3.0 marks

Consider the following functions: def p(n): if n < 10: return 1 return 1 + p(n // 10) def q(n): if n < 10: return n return n % 10 + q(n // 10) def r(n): if n <= 1: return 1 return n * r(n - 1) Which of the following function calls returns the number of digits in 50!, where n! is the factorial of n?
6406536002496.
p(q(50))
6406536002497.
q(r(50))
6406536002498.
p(r(50))
6406536002499.
r(q(50))
6406536002500.
r(p(50))

Published solution

**1. Identify the recursive functions:** p removes one decimal digit using integer division by 10 and counts one per call, so it counts digits of a nonnegative integer. q sums digits. r multiplies n by r(n-1), so it computes n factorial. **2. Compose in the requested order:** First compute 50 factorial using r(50), then count its decimal digits using p. Therefore the call is p(r(50)); its value is 65. **Answer: C — p(r(50)).** **Convention note:** The recursive returns are read inside their function bodies, with the final return following the base-case if. The PDF flattens Python indentation. A: **Incorrect:** It counts digits of the digit sum of 50, not digits of its factorial. B: **Incorrect:** It sums digits of 50 factorial rather than counting them. C: **Correct:** It first computes the factorial, then counts its decimal digits. D: **Incorrect:** It computes factorial of the digit sum 5, giving 120. E: **Incorrect:** It computes factorial of the digit count 2, giving 2.

Report a correction for Q2

Question 3 MCQ · 3.0 marks

Consider the following code snippet that writes student details to a CSV file named "employees.csv": def save_data(data): f = open('employees.csv', 'w') f.write('Name,Salary\n') for i in range(len(data)): emp, sal = data[i] row = f'{emp},{sal}' if i != len(data) - 1: row = row + '\n' f.write(row) f.close() data = [ ('Alice', 75000), ('Bob', 64000), ('Charlie', 82000), ('Diana', 71000), ('Eve', 69000) ] If the save_data(data) function is called with the list data as shown above, what will be the contents of the file "employees.csv"?
6406536002501.
Name,Salary Alice,75000 Bob,64000 Charlie,82000 Diana,71000 Eve,69000
6406536002502.
Alice,75000 Bob,64000 Charlie,82000 Diana,71000 Eve,69000
6406536002503.
Salary,Name Alice,75000 Bob,64000 Charlie,82000 Diana,71000 Eve,69000
6406536002504.
Name Salary Alice,75000 Bob,64000 Charlie,82000 Diana,71000 Eve,69000
6406536002505.
Salary,Name 75000,Alice 64000,Bob 82000,Charlie 71000,Diana 69000,Eve

Published solution

**1. Write the header:** Opening in w mode creates or truncates the file, and the first write outputs the single line “Name,Salary”. **2. Write rows in order:** Each tuple is unpacked as employee name and salary and written as name,salary. Rows are Alice,75000; Bob,64000; Charlie,82000; Diana,71000; Eve,69000. A newline is added after each row except the last. **Answer: A — Name,Salary followed by the five name,salary rows.** **Convention note:** The function’s loop body and if body are read with their intended indentation; f.close() is after the writing loop. The last data row has no trailing newline. A: **Correct:** It includes the correct header and all five rows in input order. B: **Incorrect:** It omits the header explicitly written by the function. C: **Incorrect:** It reverses the header labels without changing the data order. D: **Incorrect:** The header contains a comma, not a newline between its two words. E: **Incorrect:** It reverses both column order and the data format.

Report a correction for Q3

Question 4 MCQ · 3.0 marks

What will be the output of the following Python code? string1 = 'database' string2 = 'baseball' L = [] for i in range(len(string1)): for j in range(len(string2)): if string1[i] == string2[j]: L.append(string1[i]) break else: continue print(L)
6406536002506.
['a', 'a', 'b', 'a', 's', 'e']
6406536002507.
['a', 't', 'a', 'b', 'a', 's', 'e']
6406536002508.
['a', 'b', 'a', 's', 'e']
6406536002509.
['a', 'a', 'b', 's', 'e']

Published solution

**1. Trace each source character:** For each character in “database”, the inner loop checks whether that character appears anywhere in “baseball”. d and t have no matches; each of the three a positions matches, and b,s,e also match. **2. Preserve repeats and stop after the first match:** break prevents duplicate appends from multiple matching target positions for the same source character. It does not remove repeated a positions from the source. The result is ['a','a','b','a','s','e']. **Answer: A — ['a', 'a', 'b', 'a', 's', 'e'].** **Convention note:** The intended indentation puts append and break inside the equality test, with the loops nested. Whether the shown else attaches to that test or to the inner for does not alter this result here. A: **Correct:** It retains all matching characters in source order, including all three a occurrences. B: **Incorrect:** t does not appear in baseball and cannot be appended. C: **Incorrect:** It wrongly removes one repeated a. D: **Incorrect:** It wrongly removes one repeated a before s.

Report a correction for Q4

Question 5 MCQ · 3.0 marks

What is the output of the following snippet of code? sentence = 'python,is,fun,and,learning,python,is,great' D = dict() for word in sentence.split(','): for char in word: if char not in D: D[char] = 0 D[char] += 1 mchar, mval = '', 0 alpha = 'abcdefghijklmnopqrstuvwxyz' for char in alpha: if char not in D: continue if D[char] >= mval: mval = D[char] mchar = char print(mchar)
6406536002510.
n
6406536002511.
o
6406536002512.
i
6406536002513.
p

Published solution

**1. Build the frequencies:** Splitting removes the comma separators from the character count. Across the words, n appears 6 times; t,i,a each appear 3 times; o and p each appear twice. **2. Select the maximum:** Scanning the alphabet updates the winner whenever its count is at least the stored maximum. That tie rule would prefer the later letter on a tie, but n is the unique maximum, so the output is n. **Answer: A — n.** **Convention note:** The counting increment is inside the character loop but outside the initialization if; the PDF flattens these block indents. A: **Correct:** n has the highest count, 6. B: **Incorrect:** o occurs only twice. C: **Incorrect:** i occurs three times, below n. D: **Incorrect:** p occurs twice, below n.

Report a correction for Q5

Question 6 MCQ · 3.0 marks

If n is a positive integer, what does the following snippet compute? Q = [x for x in range(1, 3 * n + 1) if x % 3 == 0] print(sum(Q))
6406536002514.
1+2+3+…+n
6406536002515.
3+6+9+…+3n
6406536002516.
1+2+3+…+3n
6406536002517.
1+3+5+…+(2n+1)
6406536002518.
1+3+5+…+(3n+1)

Published solution

**1. Identify the selected integers:** range(1,3n+1) includes 1 through 3n. The divisibility condition keeps exactly \(3,6,9,\ldots,3n\). **2. Sum the progression:** The program prints \(3(1+2+\cdots+n)=3n(n+1)/2\), corresponding to B. **Answer: B — 3+6+9+…+3n.** A: **Incorrect:** It omits the factor of 3. B: **Correct:** It lists exactly the multiples retained by the comprehension. C: **Incorrect:** It sums all integers, not just multiples of 3. D: **Incorrect:** It describes odd integers rather than multiples of 3. E: **Incorrect:** It also describes an odd-number progression rather than the selected list.

Report a correction for Q6

Question 7 MCQ · 3.0 marks

Consider the following snippets of code: **Code-1** T = (4, 5, 6) T[0] = 10 **Code-2** S = set() S.insert(2) **Code-3** L = [] L.append(3) Select the most appropriate statement.
6406536002519.
Only code-1 will throw an error in line-2
6406536002520.
Only code-2 will throw an error in line-2
6406536002521.
Only code-3 will throw an error in line-2
6406536002522.
Code-1 and Code-2 will throw an error line-2
6406536002523.
Code-2 and Code-3 will throw an error in line-2
6406536002524.
All three code snippets will throw an error in line-2

Published solution

**1. Check the tuple and set snippets:** Assigning T[0]=10 raises TypeError because tuples are immutable. Sets have add(), not insert(), so S.insert(2) raises AttributeError. **2. Check the list snippet:** L.append(3) is a valid list mutation. Therefore exactly Code-1 and Code-2 fail on their second line. **Answer: D — Code-1 and Code-2 will throw an error line-2.** A: **Incorrect:** Code-2 fails as well. B: **Incorrect:** Code-1 fails as well. C: **Incorrect:** Code-3 is valid; the other two fail. D: **Correct:** It identifies precisely the immutable-item assignment and nonexistent set method. E: **Incorrect:** Code-3 does not fail, while Code-1 does. F: **Incorrect:** The list append is valid.

Report a correction for Q7

Question 8 MSQ · 3.0 marks

employees is a list of tuples. Each tuple is of the form (name, salary) . Select all snippets of code that create a list high_earners that contains the names of employees whose salary is above 70,000. A sample list employees and the expected output is given below. You can assume that employees is already available to you. **Sample Input** employees = [ ('Alice', 75000), ('Bob', 64000), ('Charlie', 82000), ('Diana', 71000), ('Eve', 69000) ] **Sample Output** ['Alice', 'Charlie', 'Diana']
6406536002525.
high_earners = [name for (name, salary) in employees if salary > 70000] print(high_earners)
6406536002526.
high_earners = [] for (name, salary) in employees: if salary > 70000: high_earners.append(name) print(high_earners)
6406536002527.
high_earners = [name if salary > 70000 for (name, salary) in employees] print(high_earners)
6406536002528.
high_earners = [name for (name, salary) in employees] print(high_earners)

Published solution

**1. State the filter and output:** Each employee tuple must be unpacked, tested with salary>70000, and contribute only the name. The sample retains Alice, Charlie and Diana. **2. Compare implementations:** A puts the filter after the for clause in a valid comprehension. B performs the same filter and append in a loop. C has invalid conditional-expression syntax; D omits the filter. **Answer: A, B — high_earners = [name for (name, salary) in employees if salary > 70000] ; high_earners = [] .** **Convention note:** Read B’s append inside the if and the if inside the loop, as the displayed nested snippet indicates. A: **Correct:** It is the correct filtered name comprehension. B: **Correct:** Its loop appends exactly the names passing the salary test. C: **Incorrect:** A conditional expression in this position needs an else; this is invalid syntax. D: **Incorrect:** It returns every employee name, including Bob and Eve.

Report a correction for Q8

Question 9 MSQ · 3.0 marks

Consider the following snippet: f = open('employees.csv', 'r') D = dict() for line in f: name, department, salary = line.strip().split(',') salary = int(salary) if name not in D: D[name] = dict() D[name][department] = salary print(D) This code produces the given output: {'Alice': {'HR': 70000, 'IT': 80000}, 'Bob': {'Finance': 65000, 'IT': 72000}} Which of the following could be the contents of the file employees.csv ? Select all possible answers. Note that dictionaries store keys from left to right in the order in which they are inserted. Once a key has been inserted into a dictionary, its order with respect to other keys doesn't change, unless it is deleted and reinserted.
6406536002529.
Alice,HR,70000 Bob,Finance,65000 Alice,IT,80000 Bob,IT,72000
6406536002530.
Alice,HR,70000 Bob,Finance,66000 Alice,IT,80000 Bob,IT,72000 Bob,Finance,65000
6406536002531.
Bob,Finance,65000 Bob,IT,72000 Alice,HR,70000 Alice,IT,80000
6406536002532.
Alice,IT,80000 Alice,HR,70000 Bob,Finance,65000 Bob,IT,72000

Published solution

**1. Track both levels of insertion order:** Alice must first appear before Bob; Alice’s first department must be HR before IT, and Bob’s Finance before IT. Later assignments to an existing key replace its value without moving it. **2. Check the files:** A establishes the required order and values. B first sets Bob/Finance to 66000 but later overwrites it with 65000, preserving the insertion order. C inserts Bob first; D inserts Alice’s IT before HR. **Answer: A, B — Alice,HR,70000 ; Alice,HR,70000 .** **Convention note:** The assignments are read inside the file loop, with inner-dictionary initialization conditional on a new name. The file has no header because every third field is converted directly to int. A: **Correct:** It produces the required nested key order and final values. B: **Correct:** Its later Finance row overwrites 66000 with 65000 without changing key order. C: **Incorrect:** It places Bob before Alice in the printed outer dictionary. D: **Incorrect:** It places IT before HR in Alice’s inner dictionary.

Report a correction for Q9

Question 10 MSQ · 3.0 marks

Consider the following snippet of code: def analyze_string(t, k): freq = {} for ch in t: freq[ch] = freq.get(ch, 0) + 1 is_unique = all(c < k for c in freq.values()) if is_unique: print(True) else: print(False) if input_str.isdigit(): print(True) else: print(False) analyze_string(input_str, 2) input_str is a string variable that has already been defined. The above code runs without any errors. The output when the code given above is executed is as follows: True True Which of the following statements are True? Note that your answer should hold for any value of the string input_str that results in the above output.
6406536002533.
input_str contains only numeric characters
6406536002534.
input_str could contain alphabets
6406536002535.
The first character of input_str occurs exactly two times
6406536002536.
All elements of input_str occur exactly one time
6406536002537.
All elements in input_str occur at least two times.

Published solution

**1. Interpret the frequency result:** With k=2, all(c<2 for c in freq.values()) is true exactly when every character that occurs has count 1. Thus no character is repeated. **2. Interpret isdigit:** The other True requires a nonempty string consisting entirely of digit characters. Therefore the qualifying strings contain only digits and each character occurs once. **Answer: A, D — input_str contains only numeric characters; All elements of input_str occur exactly one time.** **Convention note:** Python isdigit includes some Unicode digit characters beyond ASCII 0–9. “Numeric characters” in A is used broadly; the precise predicate is digit characters, not every Unicode numeric symbol. The question assumes the implied function/block indentation. A: **Correct:** isdigit() being true ensures all characters are digits. B: **Incorrect:** Alphabetic characters would make isdigit() false. C: **Incorrect:** The all-counts-below-2 test forbids a count of exactly two. D: **Correct:** Every present character has a positive count less than 2, hence exactly one. E: **Incorrect:** Every count is 1, the opposite of at least two.

Report a correction for Q10

Question 11 NAT · 3.0 marks

What is the output of the following snippet of code? def g(x, y): if x == 1: return 0 return 1 + g(x // y, y) print(g(1024, 2))

Published solution

**1. Follow the divisions:** The recursive arguments are 1024,512,256,128,64,32,16,8,4,2,1. The base call at x=1 returns zero. **2. Count non-base calls:** Each preceding call adds 1, so ten divisions by 2 yield a total of 10. Equivalently 1024=2 to the power 10. **Answer: 10.**

Report a correction for Q11

Question 12 NAT · 3.0 marks

What is the output of the following snippet of code? total = 0 errors = 0 for s in ['5', '2.5', '7', '8']: try: n = int(s) total += n except: errors += 1 total += 5 print(total + errors)

Published solution

**1. Process successful conversions:** int converts “5”, “7” and “8”, contributing 5+7+8=20. int("2.5") raises ValueError because it is not an integer-format string. **2. Process the exception:** The except block increments errors once and adds the fallback 5 to total. Thus total=25 and errors=1. **3. Evaluate the final expression:** total+errors=25+1=26. **Answer: 26.** **Convention note:** The fallback total+=5 is read inside the except block. If it were outside try/except and executed for every input, the result would differ; the PDF does not preserve indentation.

Report a correction for Q12

Question 13 NAT · 3.0 marks

What is the output of the following snippet of code? total = 0 num = 10 while num <= 20: count = 0 for i in range(1, num + 1): if num % i == 0: count += 1 if count == 2: total += num num += 1 print(total)

Published solution

**1. Interpret the divisor count:** For each integer from 10 through 20 inclusive, the inner loop counts its positive divisors. Exactly two divisors means the number is prime. **2. Identify and add the qualifying values:** The primes in this range are 11,13,17,19. Their sum is 11+13+17+19=60. **Answer: 60.** **Convention note:** The count==2 test occurs after finishing the divisor loop; num increments once per while iteration. These are the intended block levels in the flattened PDF.

Report a correction for Q13

Question 14 NAT · 3.0 marks

Consider the following snippet of code: L = [2, 3, 4] S = [] T = 0 i = 0 while i < len(L): S += L[:i] + L[i:] for j in S: T += j i += 1 What will be the value of T at the end of execution of the above code?

Published solution

**1. Simplify the slices:** For each i=0,1,2, L[:i]+L[i:] reconstructs the full list [2,3,4], whose sum is 9. The += operation extends S rather than resetting it. **2. Track cumulative S:** The three passes make S contain one, two and three copies of L, with sums 9,18,27 respectively. Each pass adds the sum of the entire current S to T. **3. Add the contributions:** T=9+18+27=54. **Answer: 54.** **Convention note:** The for j in S loop runs inside the while, and i increments once after that for loop. The PDF flattens the indentation.

Report a correction for Q14

Question 15 NAT · 3.0 marks

What is the output of the following snippet of code? def doSomething(x, y): if x < y: return 0 return 1 + doSomething(x // y, y) log1 = doSomething(81, 3) log2 = doSomething(64, 2) log3 = doSomething(125, 5) print(log1 + log2 + log3)

Published solution

**1. Identify the recurrence:** Each non-base call adds 1 and divides x by y using floor division until x<y. For exact powers x=y to the power k, the result is k. **2. Trace the three powers:** 81=3 to the power 4 gives 4; 64=2 to the power 6 gives 6; 125=5 to the power 3 gives 3. **3. Sum the results:** The printed value is 4+6+3=13. **Answer: 13.**

Report a correction for Q15

Question 16 MCQ · 2.0 marks

You are inside the lift of a building. There are 8 levels in the building: [−3,−2,−1,0,1,2,3,4] The number 0 is the ground floor. Positive numbers correspond to floors above the ground floor, negative numbers correspond to basement levels below the ground floor. The lift has only two buttons. The button U will take you one level up and the button D will take you one level down. You make a sequence of presses. # presses contains the sequence of button presses made by you presses = 'UDDUUUDDUDU' floor = 0 index = 0 while index < len(presses): char = presses[index] if char == 'U': floor += 1 elif char == 'D': floor -= 1 if floor == 2: print(index + 1) break index += 1 Based on the above data answer the subsequent questions.
What is the given code snippet printing?
6406536002543.
It prints the number of button presses after which you reach the floor 2 for the first time.
6406536002544.
It prints the number of times you cross the floor 2.
6406536002545.
It prints the final floor level after all the button presses.
6406536002546.
None of these.

Published solution

**1. Follow the prefix of presses:** Starting at floor 0, the first six presses U,D,D,U,U,U give floors 1,0,-1,0,1,2. **2. Interpret the stop condition:** At the first visit to floor 2, the program prints index+1, the number of presses consumed, and immediately breaks. It does not process the rest of the sequence. **Answer: A — It prints the number of button presses after which you reach the floor 2 for the first .** **Convention note:** Read the floor updates and the floor==2 check inside the while loop, and break inside that check. A: **Correct:** It describes the first hitting-time count printed before break. B: **Incorrect:** The code does not count repeated crossings and stops at the first hit. C: **Incorrect:** It stops early and prints a press count rather than the final floor. D: **Incorrect:** A correctly describes the program.

Report a correction for Q16

Question 17 NAT · 2.0 marks

You are inside the lift of a building. There are 8 levels in the building: [−3,−2,−1,0,1,2,3,4] The number 0 is the ground floor. Positive numbers correspond to floors above the ground floor, negative numbers correspond to basement levels below the ground floor. The lift has only two buttons. The button U will take you one level up and the button D will take you one level down. You make a sequence of presses. # presses contains the sequence of button presses made by you presses = 'UDDUUUDDUDU' floor = 0 index = 0 while index < len(presses): char = presses[index] if char == 'U': floor += 1 elif char == 'D': floor -= 1 if floor == 2: print(index + 1) break index += 1 Based on the above data answer the subsequent questions.
What is the output of this snippet of code?

Published solution

**1. Follow the prefix of presses:** Starting at floor 0, the first six presses U,D,D,U,U,U give floors 1,0,-1,0,1,2. **2. Interpret the stop condition:** At the first visit to floor 2, the program prints index+1, the number of presses consumed, and immediately breaks. It does not process the rest of the sequence. **3. Read the output:** Floor 2 is first reached at zero-based index 5, so the printed one-based count is 6. **Answer: 6.**

Report a correction for Q17

Question 18 MCQ · 2.0 marks

Consider the following snippet: def ProcedureOne(M): n = len(M) for i in range(n): temp = M[i][i] M[i][i] = M[i][-i - 1] M[i][-i - 1] = temp return M def ProcedureTwo(M): p = 1 n = len(M) for i in range(n): p *= M[i][i] return p M = [[2, 4, 6], [8, 10, 12], [14, 16, 18]] P = ProcedureOne(M) print(P) print(ProcedureTwo(P)) Based on the above code answer the subsequent questions.
What is the first line of output?
6406536002548.
[[6, 4, 2], [8, 10, 12], [18, 16, 14]]
6406536002549.
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
6406536002550.
[[14, 16, 18], [8, 10, 12], [2, 4, 6]]
6406536002551.
[[2, 6, 4], [8, 12, 10], [14, 18, 16]]

Published solution

**1. Swap the two diagonal positions within each row:** At i=0, columns 0 and -1 exchange 2 and 6. At i=1, columns 1 and -2 are the same middle position, so nothing changes. At i=2, columns 2 and -3 exchange 18 and 14. **2. Read the mutated matrix:** P is [[6,4,2],[8,10,12],[18,16,14]]. The operation swaps the main- and anti-diagonal entries row by row; it does not reverse the entire row order. **Answer: A — [[6, 4, 2], [8, 10, 12], [18, 16, 14]].** **Convention note:** Return M occurs after the full loop in ProcedureOne. The PDF flattens the function/loop indentation; reading return inside the loop would stop too early. A: **Correct:** It contains the correctly swapped row-end diagonal entries. B: **Incorrect:** It incorrectly leaves the original matrix unchanged. C: **Incorrect:** It reverses the row order, which the procedure never does. D: **Incorrect:** It swaps the wrong within-row positions.

Report a correction for Q18

Question 19 NAT · 2.0 marks

Consider the following snippet: def ProcedureOne(M): n = len(M) for i in range(n): temp = M[i][i] M[i][i] = M[i][-i - 1] M[i][-i - 1] = temp return M def ProcedureTwo(M): p = 1 n = len(M) for i in range(n): p *= M[i][i] return p M = [[2, 4, 6], [8, 10, 12], [14, 16, 18]] P = ProcedureOne(M) print(P) print(ProcedureTwo(P)) Based on the above code answer the subsequent questions.
What is the second line of output?

Published solution

**1. Swap the two diagonal positions within each row:** At i=0, columns 0 and -1 exchange 2 and 6. At i=1, columns 1 and -2 are the same middle position, so nothing changes. At i=2, columns 2 and -3 exchange 18 and 14. **2. Read the mutated matrix:** P is [[6,4,2],[8,10,12],[18,16,14]]. The operation swaps the main- and anti-diagonal entries row by row; it does not reverse the entire row order. **3. Multiply the new main diagonal:** ProcedureTwo multiplies P[0][0],P[1][1],P[2][2], giving 6×10×14=840. **Answer: 840.** **Convention note:** ProcedureTwo returns p after completing its loop, so all three diagonal entries contribute.

Report a correction for Q19