0% found this document useful (0 votes)
3 views55 pages

Python CS Exam Questions

The document is a comprehensive exam preparation guide for Python programming, featuring 200 high-yield practice questions across various topics such as data types, control flow, and functions. Each question includes detailed solutions and explanations, covering areas like predicting outputs, identifying errors, and programming problems. The guide aims to help learners enhance their Python skills through practical exercises and real-life scenarios.

Uploaded by

mattysiva366
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views55 pages

Python CS Exam Questions

The document is a comprehensive exam preparation guide for Python programming, featuring 200 high-yield practice questions across various topics such as data types, control flow, and functions. Each question includes detailed solutions and explanations, covering areas like predicting outputs, identifying errors, and programming problems. The guide aims to help learners enhance their Python skills through practical exercises and real-life scenarios.

Uploaded by

mattysiva366
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Complete Exam Preparation Guide

200 High-Yield Practice Questions with Detailed Solutions

Topic Questions

1. Data Types, Variables, Operators, Control Flow Q1 – Q50

2. Strings, Text Files, OS/SYS Modules Q51 – Q100

3. Lists, Tuples, and Dictionaries Q101 – Q150

4. Functions, OOP, Recursion Q151 – Q200

Blueprint Coverage: Predict Output | Identify Error Type | Error Correction | Programming Problems
TOPIC 1: Data Types, Variables, Operators, Control Flow

Section A – Predict the Output


Q1. What is the output of the following code?
x = 10
y = 3
print(x // y, x % y, x ** y)

✔ Answer: 3 1 1000
■ Explanation: // is floor division (10//3=3), % is modulus (10%3=1), ** is exponentiation (10**3=1000).

Q2. Predict the output:


a = True
b = False
print(a and b, a or b, not a)

✔ Answer: False True False


■ Explanation: 'and' returns True only if both are True. 'or' returns True if at least one is True. 'not' flips the
boolean.

Q3. What will be printed?


x = 5
x += 3
x *= 2
print(x)

✔ Answer: 16
■ Explanation: x starts as 5, +=3 makes it 8, *=2 makes it 16. Compound assignment operators modify
in-place.

Q4. Predict the output:


for i in range(1, 10, 3):
print(i, end=' ')

✔ Answer: 1 4 7
■ Explanation: range(1,10,3) generates 1, 4, 7 (start=1, stop=10 exclusive, step=3).

Q5. What is the output?


x = 15
if x > 10:
if x > 20:
print("A")
else:
print("B")
else:
print("C")

✔ Answer: B
■ Explanation: 15>10 is True so outer if executes. 15>20 is False so inner else executes printing 'B'.

Q6. Predict the output:


i = 0
while i < 5:
if i == 3:
break
print(i, end=' ')
i += 1

✔ Answer: 0 1 2
■ Explanation: Loop starts at 0. When i==3, break exits the loop. So 0,1,2 are printed before break.

Q7. What will be printed?


x = 7
print(type(x), type(float(x)), type(str(x)))

✔ Answer:
■ Explanation: type() returns the data type. float(7) converts to 7.0, str(7) converts to '7'.

Q8. Predict the output:


for i in range(5):
if i % 2 == 0:
continue
print(i, end=' ')

✔ Answer: 1 3
■ Explanation: continue skips the current iteration. Even numbers (0,2,4) are skipped. Only odd numbers 1
and 3 are printed.

Q9. What is the output?


x = 10
y = 0
print(x > 5 and y != 0)
print(x > 5 or y != 0)

✔ Answer: False True


■ Explanation: First: x>5 is True but y!=0 is False; True and False = False. Second: x>5 is True; True or
anything = True.

Q10. Predict the output (short-circuit evaluation):


def check():
print("called")
return True

x = 0
if x != 0 and check():
print("yes")
else:
print("no")

✔ Answer: no
■ Explanation: Short-circuit: x!=0 is False, so Python never calls check(). The 'and' short-circuits, 'called' is
never printed.

Section B – Identify the Error


Q11. Identify the error type:
x = 10
y = "5"
print(x + y)

✔ Answer: TypeError
■ Explanation: You cannot add int and str directly. Use int(y) or str(x) to convert first: print(x + int(y)) gives 15.

Q12. What error does this produce?


print(result)
result = 42

✔ Answer: NameError: name 'result' is not defined


■ Explanation: Variables must be assigned before use. 'result' is used before assignment, causing
NameError.

Q13. Identify the error:


x = 10
y = 0
print(x / y)

✔ Answer: ZeroDivisionError: division by zero


■ Explanation: Dividing any number by zero raises ZeroDivisionError. Use a check: if y != 0 before dividing.

Q14. What type of error is this?


if True
print("Hello")

✔ Answer: SyntaxError: expected ':'


■ Explanation: 'if' statement requires a colon ':' at the end. Correct: if True:

Q15. Identify the error:


x = int("hello")

✔ Answer: ValueError: invalid literal for int() with base 10: 'hello'
■ Explanation: int() can only convert numeric strings like '42'. 'hello' is not a valid integer string.

Section C – Error Correction


Q16. Fix the error in this code:
for i in range(10)
if i % 2 = 0:
print(i)

✔ Answer: for i in range(10): if i % 2 == 0: print(i)


■ Explanation: Two errors: missing colon after range(10), and = is assignment; use == for comparison.

Q17. Correct this immutable variable mistake:


PI = 3.14159
PI = 3.14 # accidentally changed
■ Explanation: Python doesn't enforce immutability. Use naming convention (ALL_CAPS) as a signal. To truly
enforce, use: from typing import Final; PI: Final = 3.14159

Q18. Fix the indentation error:


x = 5
if x > 3:
print("Greater")

✔ Answer: x = 5 if x > 3: print("Greater")


■ Explanation: Python uses indentation to define blocks. The print statement must be indented (4 spaces)
inside the if block.

Section D – Programming Problems


Q19. [Real-Life] A temperature sensor reads values in Celsius. Write a program to convert it to
Fahrenheit and classify it as 'Cold' (<15), 'Warm' (15-30), or 'Hot' (>30).
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"Fahrenheit: {fahrenheit:.2f}")
if celsius < 15:
print("Cold")
elif celsius <= 30:
print("Warm")
else:
print("Hot")
■ Explanation: The formula F = (C × 9/5) + 32 converts Celsius to Fahrenheit. Chained if-elif-else classifies
the temperature.

Q20. [Case-Based] A bank applies 5% interest if balance > 10000, else 3%. Calculate and print
the interest for a given balance.
balance = float(input("Enter balance: "))
rate = 0.05 if balance > 10000 else 0.03
interest = balance * rate
print(f"Interest Rate: {rate*100}%")
print(f"Interest Earned: {interest:.2f}")
■ Explanation: Ternary (conditional) expression: value_if_true if condition else value_if_false. Cleaner than
full if-else for simple assignments.

Q21. Write a program to print the multiplication table of a number using a for loop.
n = int(input("Enter number: "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
■ Explanation: range(1,11) generates 1 through 10. f-strings format the output neatly. This is a classic loop
application.

Q22. Use a while loop to find the sum of digits of a number. E.g., 123 → 6.
n = int(input("Enter a number: "))
total = 0
while n > 0:
total += n % 10 # get last digit
n //= 10 # remove last digit
print("Sum of digits:", total)
■ Explanation: n%10 extracts the last digit. n//10 removes it. Repeat until n becomes 0.

Q23. [Predict Output] What does this print?


x = 5
y = 2
print(x > y, x == y, x != y, x >= y)

✔ Answer: True False True True


■ Explanation: 5>2=True, 5==2=False, 5!=2=True, 5>=2=True. Comparison operators return boolean values.

Q24. Write a program to check if a number is positive, negative, or zero using if-elif-else.
n = float(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
■ Explanation: elif (else if) allows multiple mutually exclusive conditions. Only one branch executes.

Q25. [Real-Life] ATM: Ask user for PIN (stored as 1234). Give 3 attempts. Lock account after 3
failures.
stored_pin = 1234
attempts = 0
while attempts < 3:
pin = int(input("Enter PIN: "))
if pin == stored_pin:
print("Access Granted!")
break
else:
attempts += 1
print(f"Wrong PIN. {3 - attempts} attempts left.")
else:
print("Account Locked!")
■ Explanation: while-else: the else block runs only if the loop completes without break. This elegantly handles
the lock scenario.

Q26. Print all numbers from 1-100 divisible by both 3 and 5.


for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print(i, end=' ')

✔ Answer: 15 30 45 60 75 90
■ Explanation: A number is divisible by both 3 and 5 if it's divisible by 15 (LCM). The 'and' operator requires
both conditions.

Q27. [Predict Output] Nested loop pattern:


for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=' ')
print()

✔ Answer: 1 2 3 2 4 6 3 6 9
■ Explanation: Nested loops: outer i goes 1,2,3; inner j goes 1,2,3. Each row is i*j. \t is tab, print() adds
newline.
Q28. Find the largest of three numbers using if-elif-else without using max().
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if a >= b and a >= c:
print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)
■ Explanation: Compare each to the other two using 'and'. The one satisfying both comparisons is largest.

Q29. [Error] Identify and fix:


age = input("Enter age: ")
if age >= 18:
print("Adult")

✔ Answer: TypeError: input() returns str, cannot compare with int. Fix: age = int(input('Enter age:
'))
■ Explanation: Always convert input() to the required type (int/float) before numeric operations.

Q30. [Real-Life] A store gives 10% discount if purchase > 500, else 5%. Calculate final price.
purchase = float(input("Purchase amount: "))
discount = 0.10 if purchase > 500 else 0.05
final = purchase - (purchase * discount)
print(f"Discount: {discount*100:.0f}%")
print(f"Final Price: Rs.{final:.2f}")
■ Explanation: Real-life discounting: subtract (amount * rate) from original. Ternary operator selects the rate.

Q31. Write a program to print a right-angled triangle of stars with n rows.


n = int(input("Enter rows: "))
for i in range(1, n+1):
print('*' * i)
■ Explanation: String multiplication: '*' * i prints i stars. Loop i from 1 to n gives increasing rows.

Q32. [Predict Output] Range with negative step:


for i in range(10, 0, -2):
print(i, end=' ')

✔ Answer: 10 8 6 4 2
■ Explanation: range(10, 0, -2) counts down from 10 to 1 (exclusive of 0) in steps of 2.

Q33. Check if a year is a leap year.


year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
■ Explanation: Leap year: divisible by 4 but not 100, OR divisible by 400. E.g., 2000=leap, 1900=not leap,
2024=leap.
Q34. [Case-Based] Electricity bill: 0-100 units=Rs.1.5/unit, 101-200=Rs.2.5, above 200=Rs.4.
Calculate bill.
units = int(input("Units consumed: "))
if units <= 100:
bill = units * 1.5
elif units <= 200:
bill = 100 * 1.5 + (units - 100) * 2.5
else:
bill = 100 * 1.5 + 100 * 2.5 + (units - 200) * 4
print(f"Electricity Bill: Rs.{bill:.2f}")
■ Explanation: Slab-based billing: first 100 at 1.5, next 100 at 2.5, remainder at 4. Each slab's cost is
accumulated.

Q35. Predict the output of this while loop with else:


i = 1
while i <= 5:
print(i, end=' ')
i += 1
else:
print("Done")

✔ Answer: 1 2 3 4 5 Done
■ Explanation: while-else: the else clause runs when the condition becomes False (normal exit). 'Done' prints
after the loop.

Q36. Write a program to count how many times a digit appears in a number.
n = input("Enter a number: ")
d = input("Enter digit to count: ")
count = [Link](d)
print(f"Digit {d} appears {count} times in {n}")
■ Explanation: Treating numbers as strings lets us use .count() directly. This avoids complex loop logic.

Q37. [Error Correction] Fix this number guessing game:


import random
secret == [Link](1, 100) # Error 1
guess = int(input("Guess: "))
if guess = secret: # Error 2
print("Correct!")

✔ Answer: Line 2: = not ==. Line 4: == not =. Fix: secret = [Link](1,100) and if guess ==
secret:
■ Explanation: = is assignment, == is comparison. Mixing them is one of the most common Python beginner
errors.

Q38. [Real-Life] A parking lot charges Rs.20 for the first hour and Rs.10 for each additional
hour. Calculate the fee.
hours = int(input("Hours parked: "))
if hours <= 0:
fee = 0
elif hours == 1:
fee = 20
else:
fee = 20 + (hours - 1) * 10
print(f"Parking Fee: Rs.{fee}")
■ Explanation: Real-world rate calculation: base rate + extra hours * per-hour rate. Validate for 0 or negative
hours.

Q39. What is the output?


x = 100
y = 200
print(x == 100, y > 100, x + y == 300)

✔ Answer: True True True


■ Explanation: x==100 is True, y>100 is True (200>100), x+y==300 is True (300==300). All comparisons
evaluate correctly.

Q40. Write a program to print all prime numbers between 1 and 50.
for num in range(2, 51):
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=' ')
■ Explanation: A prime has no divisors except 1 and itself. We only need to check up to sqrt(num). Inner
break exits on first factor found.

Q41. [Predict] What does this print?


x = 5
print(bool(x), bool(0), bool(''), bool('hi'), bool([]))

✔ Answer: True False False True False


■ Explanation: Falsy values in Python: 0, '', [], {}, None, False. Everything else is truthy. bool() converts to
boolean.

Q42. Correct this infinite loop:


i = 1
while i <= 10:
print(i)
# forgot to increment i

✔ Answer: Add i += 1 inside the loop after print(i).


■ Explanation: Without i += 1, i stays 1 forever, causing an infinite loop. Always ensure the loop condition can
eventually become False.

Q43. [Case-Based] BMI Calculator: weight(kg)/height(m)^2. Classify: <18.5=Underweight,


18.5-24.9=Normal, 25-29.9=Overweight, >=30=Obese.
weight = float(input("Weight (kg): "))
height = float(input("Height (m): "))
bmi = weight / (height ** 2)
print(f"BMI: {bmi:.2f}")
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Normal weight")
elif bmi < 30:
print("Overweight")
else:
print("Obese")
■ Explanation: BMI formula is standard medical metric. Chained elif handles mutually exclusive ranges
cleanly.

Q44. What is the output?


for i in range(3):
print(i)
else:
print("loop ended")

✔ Answer: 0 1 2 loop ended


■ Explanation: for-else: the else runs after the loop completes normally (without break). Useful for search
loops.

Q45. [Real-Life] Simple grade calculator: marks out of 100. >=90=A, >=80=B, >=70=C, >=60=D,
else F.
marks = int(input("Enter marks (0-100): "))
if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'
print(f"Grade: {grade}")
■ Explanation: Chained elif evaluates top-down. Once a condition matches, the rest are skipped. Order
matters!

Q46. Identify the logical error:


# Check if x is between 1 and 10
x = 5
if 1 < x < 10:
print("In range")

# Student's version (wrong):


if x > 1 and < 10: # SyntaxError
print("In range")

✔ Answer: The student's version has a SyntaxError. Correct: if x > 1 and x < 10 OR if 1 < x < 10.
■ Explanation: Python supports chained comparisons (1 < x < 10) which is elegant. If using 'and', both sides
must be complete expressions.

Q47. Write a program using a while loop to reverse a number (e.g., 12345 → 54321).
n = int(input("Enter number: "))
original = n
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n //= 10
print(f"Reverse of {original} is {rev}")
■ Explanation: Extract last digit (n%10), build reversed number by shifting left (rev*10) and adding digit.
Remove last digit (n//10).

Q48. [Predict] Short-circuit evaluation:


x = 5
print(x > 0 or 1/0)
print(x < 0 and 1/0)

✔ Answer: True False


■ Explanation: 'or': first operand True → result True without evaluating 1/0 (no error). 'and': first operand
False → result False without evaluating 1/0.

Q49. [Real-Life] A simple vending machine: items cost 25, 50, 75 cents. Accept coin and give
change.
price = int(input("Item price (25/50/75 cents): "))
coin = int(input("Insert coin (25/50/100 cents): "))
if coin >= price:
change = coin - price
print(f"Dispensing item. Change: {change} cents")
else:
print(f"Insufficient. Need {price - coin} more cents.")
■ Explanation: Real-life transaction: verify payment sufficiency, compute change. Simple but demonstrates
practical if-else usage.

Q50. Write a program to print the Fibonacci sequence up to n terms.


n = int(input("Enter number of terms: "))
a, b = 0, 1
for i in range(n):
print(a, end=' ')
a, b = b, a + b
■ Explanation: Tuple unpacking: a,b = b, a+b simultaneously updates both. Fibonacci: each term = sum of
previous two (0,1,1,2,3,5,8...).
TOPIC 2: Strings, Text Files, OS/SYS Modules

Section A – Predict the Output


Q51. Predict the output:
s = "Hello, World!"
print(s[0], s[-1], s[7:12])

✔ Answer: H ! World
■ Explanation: s[0]='H' (first char), s[-1]='!' (last char), s[7:12]='World' (slicing from index 7 to 11).

Q52. What will be printed?


s = "Python Programming"
print(len(s))
print([Link]())
print([Link]('m'))

✔ Answer: 18 PYTHON PROGRAMMING 2


■ Explanation: len() counts all characters including spaces. upper() converts to uppercase. count('m') finds
lowercase 'm' occurrences: progra'mm'ing has 2.

Q53. Predict the output:


s = " hello world "
print([Link]())
print([Link]().title())

✔ Answer: hello world Hello World


■ Explanation: strip() removes leading/trailing whitespace. title() capitalizes first letter of each word.

Q54. What is the output?


s = "apple,banana,cherry"
parts = [Link](',')
print(parts)
print(len(parts))

✔ Answer: ['apple', 'banana', 'cherry'] 3


■ Explanation: split(',') divides string at each comma, returning a list. len() counts 3 elements.

Q55. Predict the output:


name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}, Born: {2025 - age}")

✔ Answer: Name: Alice, Age: 25, Born: 2000


■ Explanation: f-strings (formatted string literals) embed variables and expressions directly inside {}.
2025-25=2000.

Q56. What does this print?


s = "Hello"
print(s * 3)
print('-' * 20)

✔ Answer: HelloHelloHello --------------------


■ Explanation: String * n repeats the string n times. Useful for creating separators or repeated patterns.

Q57. Predict the output:


s = "Python"
print(s[::2])
print(s[::-1])

✔ Answer: Pto nohtyP


■ Explanation: s[::2] takes every 2nd character: P(0),t(2),o(4). s[::-1] reverses: step=-1 goes from end to start.

Q58. What is the output?


s = "hello world"
print([Link]('world'))
print([Link]('world', 'Python'))
print([Link]('hello'))

✔ Answer: 6 hello Python True


■ Explanation: find() returns the starting index of 'world' (6). replace() returns new string. startswith() checks
prefix.

Q59. Predict output:


words = ['I', 'love', 'Python']
print(' '.join(words))
print('-'.join(words))

✔ Answer: I love Python I-love-Python


■ Explanation: join() concatenates list elements with the specified separator string. The separator goes
between elements.

Q60. What will this print?


s = "12345"
print([Link]())
s2 = "abc123"
print([Link]())
print([Link]())

✔ Answer: True False True


■ Explanation: isdigit() → True only if ALL chars are digits. isalnum() → True if all chars are letters or digits
(no spaces/symbols).

Section B – Identify Errors & Correction


Q61. Identify the error:
s = "Python"
print(s[10])

✔ Answer: IndexError: string index out of range


■ Explanation: 'Python' has indices 0-5. Index 10 doesn't exist. Always check len(s) before accessing by
index.

Q62. Fix the file writing code:


f = open("[Link]")
[Link]("Hello World")
[Link]()
✔ Answer: f = open("[Link]", "w") # mode 'w' required for writing [Link]("Hello World") [Link]()
■ Explanation: open() default mode is 'r' (read). To write, specify 'w'. Without 'w', you get
[Link] error.

Q63. Identify the error type:


s = "hello"
s[0] = "H"

✔ Answer: TypeError: 'str' object does not support item assignment


■ Explanation: Strings are immutable in Python. To change, create a new string: s = 'H' + s[1:] or use
[Link]('h','H').

Q64. [Real-Life] Fix this code that reads a file:


with open("[Link]") as f:
for line in f:
print(line)
# prints extra blank lines

✔ Answer: Use print([Link]()) to remove the trailing newline already in each line from the file.
■ Explanation: Each line in a file ends with '\n'. print() adds another '\n'. strip() removes leading/trailing
whitespace including '\n'.

Q65. What error and how to fix:


f = open("missing_file.txt", "r")
content = [Link]()

✔ Answer: FileNotFoundError. Fix: use try-except or check [Link]() first.


■ Explanation: try: f = open("missing_file.txt", "r") except FileNotFoundError: print("File not found!")

Section C – Programming Problems


Q66. [Real-Life] Count the number of words, lines, and characters in a text file.
filename = input("Enter filename: ")
with open(filename, 'r') as f:
content = [Link]()

lines = [Link]('\n')
words = [Link]()
chars = len(content)

print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {chars}")
■ Explanation: split('\n') splits by newline for line count. split() (no arg) splits by any whitespace for words.
len() counts characters.

Q67. [Case-Based] A student record is stored as 'Name,Age,Grade' per line in a CSV. Read
and display it.
with open("[Link]", "r") as f:
for line in f:
line = [Link]()
if line: # skip empty lines
name, age, grade = [Link](',')
print(f"Name: {name}, Age: {age}, Grade: {grade}")
■ Explanation: CSV parsing: strip() removes \n, split(',') extracts fields. Tuple unpacking assigns each field to
a variable.

Q68. Write a program to write 5 student names to a file, then read and print them.
# Writing
with open("[Link]", "w") as f:
for i in range(5):
name = input(f"Enter name {i+1}: ")
[Link](name + "\n")

# Reading
print("\nStudents in file:")
with open("[Link]", "r") as f:
for line in f:
print([Link]())
■ Explanation: 'with' statement auto-closes the file. 'w' mode overwrites. '\n' needed between names. 'r' mode
reads. strip() removes \n on display.

Q69. [Predict] String formatting:


pi = 3.14159265
print(f"{pi:.2f}")
print(f"{pi:.4f}")
print(f"{'hello':>10}")
print(f"{'hello':<10}|")

✔ Answer: 3.14 3.1416 hello hello |


■ Explanation: :.2f = 2 decimal places. :>10 = right-align in 10-char field. :<10 = left-align. Useful for formatted
reports.

Q70. [Real-Life] Count occurrences of each vowel in a sentence.


sentence = input("Enter a sentence: ").lower()
vowels = 'aeiou'
for v in vowels:
count = [Link](v)
if count > 0:
print(f"'{v}': {count}")
■ Explanation: .lower() ensures case-insensitive counting. .count(v) counts occurrences. Iterating over vowels
string checks each one.

Q71. Using os module: list all .txt files in the current directory.
import os
files = [Link]('.')
txt_files = [f for f in files if [Link]('.txt')]
print("Text files:", txt_files)
■ Explanation: [Link]('.') lists all files in current directory. List comprehension filters by extension using
endswith().

Q72. [Case-Based] Append a log entry with timestamp to a log file.


import os
import sys

log_file = "[Link]"
message = "Application started successfully"

with open(log_file, 'a') as f: # 'a' = append mode


[Link](f"{message}\n")

print(f"Log written to {log_file}")


print(f"File size: {[Link](log_file)} bytes")
■ Explanation: 'a' mode appends without overwriting. [Link]() returns file size. Logging is critical in
real applications.

Q73. What is the output of these string methods?


s = " Hello World "
print(repr([Link]()))
print(repr([Link]()))
print(repr([Link]()))

✔ Answer: 'Hello World' 'Hello World ' ' Hello World'


■ Explanation: strip() removes both sides. lstrip() = left strip only. rstrip() = right strip only. repr() shows the
string with quotes to reveal spaces.

Q74. [Real-Life] Search for a keyword in a file and print matching lines (like grep).
filename = input("Filename: ")
keyword = input("Search for: ")
found = False
with open(filename, 'r') as f:
for i, line in enumerate(f, 1):
if [Link]() in [Link]():
print(f"Line {i}: {[Link]()}")
found = True
if not found:
print("Keyword not found.")
■ Explanation: enumerate(f, 1) gives (line_number, line). Case-insensitive search: convert both to lower. Real
grep-like utility!

Q75. Convert a string of binary, octal, and hexadecimal to decimal.


binary = "1010"
octal = "17"
hexa = "1F"

print(int(binary, 2)) # binary to decimal


print(int(octal, 8)) # octal to decimal
print(int(hexa, 16)) # hex to decimal

# Reverse: decimal to other bases


n = 255
print(bin(n)) # 0b11111111
print(oct(n)) # 0o377
print(hex(n)) # 0xff
✔ Answer: 10 15 31 0b11111111 0o377 0xff
■ Explanation: int(str, base) converts from any base to decimal. bin(), oct(), hex() convert decimal to
binary/octal/hex with prefix.

Q76. Predict the output of string comparison:


print("apple" < "banana")
print("Python" == "python")
print("Z" > "A")

✔ Answer: True False True


■ Explanation: String comparison is lexicographic (dictionary order) based on Unicode values. 'a'<'b',
comparison is case-sensitive. 'Z'(90) > 'A'(65).

Q77. [Error] Fix this palindrome check:


word = input("Enter word: ")
if word = word[::-1]: # Error
print("Palindrome")

✔ Answer: Replace = with ==: if word == word[::-1]:


■ Explanation: = is assignment, == is comparison. word[::-1] reverses the string. If original equals reverse, it's
a palindrome (e.g., 'madam').

Q78. [Case-Based] Using [Link]: write a script that takes a name as command-line
argument.
import sys

if len([Link]) < 2:
print("Usage: python [Link] <name>")
[Link](1)

name = [Link][1]
print(f"Hello, {name}!")
■ Explanation: [Link][0] = script name, [Link][1] = first argument. [Link](1) exits with error code. Used
in CLI tools.

Q79. Write a program to count word frequency in a sentence.


sentence = input("Enter sentence: ").lower()
words = [Link]()
freq = {}
for word in words:
freq[word] = [Link](word, 0) + 1
for word, count in sorted([Link]()):
print(f"{word}: {count}")
■ Explanation: [Link](key, default) safely retrieves count (0 if not found). sorted() alphabetizes output. This
is foundational NLP!

Q80. [Real-Life] A bank statement file has lines: 'Date,Description,Amount'. Find total credit
and debit.
total_credit = 0
total_debit = 0
with open("[Link]", "r") as f:
next(f) # skip header line
for line in f:
parts = [Link]().split(',')
amount = float(parts[2])
if amount > 0:
total_credit += amount
else:
total_debit += amount
print(f"Total Credit: {total_credit:.2f}")
print(f"Total Debit: {total_debit:.2f}")
■ Explanation: next(f) skips the header row. Positive amounts = credits, negative = debits. Real financial data
processing pattern.

Q81. Predict the output of string indexing:


s = "abcdef"
print(s[1:4])
print(s[:3])
print(s[3:])
print(s[::2])

✔ Answer: bcd abc def ace


■ Explanation: s[1:4]=chars at 1,2,3. s[:3]=chars 0,1,2. s[3:]=chars 3 to end. s[::2]=every 2nd char from start.

Q82. [Real-Life] Generate a username from first name and last name (first 3 chars each +
length).
first = input("First name: ").lower()
last = input("Last name: ").lower()
username = first[:3] + last[:3] + str(len(first) + len(last))
print(f"Username: {username}")
■ Explanation: String slicing [:3] takes first 3 characters. Concatenation builds the username. Common in
user registration systems.

Q83. What is the output?


import os
path = "/home/user/documents/[Link]"
print([Link](path))
print([Link](path))
print([Link](path))

✔ Answer: [Link] /home/user/documents ('/home/user/documents/report', '.txt')


■ Explanation: basename()=filename only. dirname()=directory only. splitext()=splits name and extension.
Essential for file management.

Q84. [Case-Based] A student submits answers as a string 'ABCDA'. Compare with key
'ABCDB' and give score.
key = "ABCDB"
answers = input("Enter your answers: ").upper()
score = sum(1 for a, k in zip(answers, key) if a == k)
print(f"Score: {score}/{len(key)}")
■ Explanation: zip() pairs corresponding characters. Generator expression counts matches. sum() totals
correct answers. Clean one-liner!
Q85. Write a program to check if a string is a valid email (contains @ and .).
email = input("Enter email: ")
if '@' in email and '.' in email:
at_pos = [Link]('@')
dot_pos = [Link]('.')
if at_pos > 0 and dot_pos > at_pos + 1:
print("Valid email format")
else:
print("Invalid email")
else:
print("Invalid email - missing @ or .")
■ Explanation: Basic validation: @ must exist and come before the last dot. rfind() finds last occurrence. Real
form validation logic!

Q86. Predict the output:


s = "Hello, World!"
print([Link]())
print([Link]())
print([Link](20, '*'))

✔ Answer: hello, world! hELLO, wORLD! ***Hello, World!***


■ Explanation: lower()=all lowercase. swapcase()=flip each case. center(20,'*')=center in 20-char field
padded with '*'.

Q87. [Error Correction] Fix the file append code:


with open("[Link]", "w") as f: # should append
[Link]("New log entry\n")

✔ Answer: Change 'w' to 'a'. Mode 'w' overwrites the file; 'a' appends to it.
■ Explanation: File modes: 'r'=read, 'w'=write (overwrite), 'a'=append, 'r+'=read+write. Using 'w' erases
existing content!

Q88. [Real-Life] Copy contents of one file to another.


src = input("Source file: ")
dst = input("Destination file: ")
try:
with open(src, 'r') as f_src:
content = f_src.read()
with open(dst, 'w') as f_dst:
f_dst.write(content)
print(f"Copied {src} to {dst} successfully.")
except FileNotFoundError:
print(f"Error: {src} not found.")
■ Explanation: Read source fully, then write to destination. try-except handles missing source file gracefully.
Basic file copy utility.

Q89. What is the output?


nums = [1, 2, 3, 4, 5]
s = ', '.join(str(n) for n in nums)
print(s)
print(type(s))

✔ Answer: 1, 2, 3, 4, 5
■ Explanation: join() requires strings; str(n) converts each int. Generator expression avoids creating an
intermediate list. Result is a string.

Q90. [Case-Based] Tabulate student marks from a file and compute average.
total = 0
count = 0
with open("[Link]", "r") as f:
for line in f:
name, mark = [Link]().split(',')
mark = int(mark)
print(f"{name}: {mark}")
total += mark
count += 1
if count > 0:
print(f"Average: {total/count:.2f}")
■ Explanation: Assumes format 'Name,Mark' per line. strip() then split(',') extracts fields. Accumulate total and
count for average.

Q91. Predict the output:


s = "Python3"
print([Link]())
print([Link]())
print([Link]())
print("3".isnumeric())

✔ Answer: False False True True


■ Explanation: 'Python3': not all numeric (has letters), not all alpha (has digit), but isalnum()=True (all
alphanumeric). '3' alone is numeric.

Q92. Write a program to remove duplicate characters from a string preserving order.
s = input("Enter string: ")
seen = set()
result = ""
for char in s:
if char not in seen:
result += char
[Link](char)
print("Without duplicates:", result)
■ Explanation: Set tracks seen characters (O(1) lookup). Only add to result if not seen before. Preserves first
occurrence of each character.

Q93. [Real-Life] Password validator: min 8 chars, has uppercase, lowercase, digit.
password = input("Enter password: ")
errors = []
if len(password) < 8:
[Link]("at least 8 characters")
if not any([Link]() for c in password):
[Link]("an uppercase letter")
if not any([Link]() for c in password):
[Link]("a lowercase letter")
if not any([Link]() for c in password):
[Link]("a digit")
if errors:
print("Password must contain: " + ', '.join(errors))
else:
print("Strong password!")
■ Explanation: any() with generator: True if at least one char matches. Collecting all errors (not stopping at
first) gives better UX.

Q94. What is the output?


s = "banana"
print([Link]('a'))
print([Link]('a'))
print([Link]('a'))

✔ Answer: 1 5 3
■ Explanation: index('a') finds FIRST occurrence at index 1. rindex('a') finds LAST occurrence at index 5.
count('a') = 3 occurrences.

Q95. [Predict] String formatting with format():


print("{} is {} years old".format("Alice", 25))
print("{name} scored {score:.1f}%".format(name="Bob", score=87.5))
print("{0} and {1} and {0}".format("x", "y"))

✔ Answer: Alice is 25 years old Bob scored 87.5% x and y and x


■ Explanation: format() fills {} placeholders. Named placeholders use keyword args. Index {0},{1} allows
reuse of arguments.

Q96. [Error] Identify and fix:


with open("[Link]", "r") as f:
lines = [Link]()
print(lines[100]) # file has only 50 lines

✔ Answer: IndexError: list index out of range. Fix: check len(lines) before accessing, or use
try-except.
■ Explanation: readlines() returns a list. Accessing beyond its length causes IndexError. Always validate
index: if 100 < len(lines): print(lines[100])

Q97. Write a program to encode a message by shifting each letter by 3 (Caesar cipher).
message = input("Enter message: ")
encoded = ""
for char in message:
if [Link]():
shift = 3
base = ord('A') if [Link]() else ord('a')
encoded += chr((ord(char) - base + shift) % 26 + base)
else:
encoded += char
print("Encoded:", encoded)
■ Explanation: ord() gives ASCII value. chr() converts back. %26 wraps around alphabet. Preserve case and
non-alpha characters.

Q98. [Real-Life] Use os module to create a directory and check if it exists.


import os

folder = "my_project"
if not [Link](folder):
[Link](folder)
print(f"Created folder: {folder}")
else:
print(f"Folder already exists: {folder}")

print("Current directory:", [Link]())


print("Contents:", [Link]('.'))
■ Explanation: [Link]() checks existence. makedirs() creates directory (and parents). getcwd() =
current working directory.

Q99. Predict the output:


s = "Hello World"
words = [Link]()
[Link]()
print(' '.join(words))

✔ Answer: Hello World


■ Explanation: split() gives ['Hello','World']. sort() alphabetically: H comes before W so order unchanged.
join() reassembles.

Q100. [Case-Based] A receipt stored as text: 'Item:Price'. Extract all prices and compute total.
total = 0.0
with open("[Link]", "r") as f:
for line in f:
if ':' in line:
item, price = [Link]().split(':')
price = float([Link]())
print(f"{[Link]()}: Rs.{price:.2f}")
total += price
print(f"Total: Rs.{total:.2f}")
■ Explanation: split(':') separates item and price. strip() cleans extra spaces. Accumulate prices to compute
total. Real billing system logic!
TOPIC 3: Lists, Tuples, and Dictionaries

Section A – Predict the Output


Q101. Predict the output:
lst = [10, 20, 30, 40, 50]
print(lst[1])
print(lst[-2])
print(lst[1:4])
print(lst[::2])

✔ Answer: 20 40 [20, 30, 40] [10, 30, 50]


■ Explanation: lst[1]=20, lst[-2]=40 (2nd from end), lst[1:4]=[20,30,40], lst[::2]= every other element starting
from 0.

Q102. What is the output?


lst = [3, 1, 4, 1, 5, 9, 2, 6]
[Link]()
print(lst)
[Link](reverse=True)
print(lst)

✔ Answer: [1, 1, 2, 3, 4, 5, 6, 9] [9, 6, 5, 4, 3, 2, 1, 1]


■ Explanation: sort() modifies list in-place ascending. reverse=True sorts descending. Both preserve
duplicate values.

Q103. Predict the output:


lst = [1, 2, 3]
[Link](4)
[Link](1, 10)
print(lst)
[Link](3)
print(lst)

✔ Answer: [1, 10, 2, 3, 4] [1, 10, 2, 4]


■ Explanation: append(4) adds to end. insert(1,10) inserts 10 at index 1. remove(3) removes first occurrence
of value 3.

Q104. What will be printed?


t = (1, 2, 3, 4, 5)
print(t[1:3])
print(t[-1])
print(len(t))
print(sum(t), max(t), min(t))

✔ Answer: (2, 3) 5 5 15 5 1
■ Explanation: Tuples support all indexing/slicing like lists. sum(), max(), min() work on any iterable. Tuples
are immutable.

Q105. Predict the output:


d = {'name': 'Alice', 'age': 25, 'grade': 'A'}
print(d['name'])
print([Link]('score', 0))
print(list([Link]()))
print(list([Link]()))

✔ Answer: Alice 0 ['name', 'age', 'grade'] ['Alice', 25, 'A']


■ Explanation: d['name'] accesses value. get('score',0) returns 0 (default) if key missing. keys() and values()
return view objects; list() converts them.

Q106. What is the output?


lst = [1, [2, 3], [4, [5, 6]]]
print(lst[1])
print(lst[1][0])
print(lst[2][1][1])

✔ Answer: [2, 3] 2 6
■ Explanation: Nested list access: lst[1]=[2,3], lst[1][0]=2, lst[2]=[4,[5,6]], lst[2][1]=[5,6], lst[2][1][1]=6.

Q107. Predict the output:


a = [1, 2, 3]
b = a # reference copy
c = a[:] # shallow copy
[Link](4)
print(b)
print(c)

✔ Answer: [1, 2, 3, 4] [1, 2, 3]


■ Explanation: b = a makes b point to same list (alias). c = a[:] makes independent copy. Appending to a
affects b but not c.

Q108. What will be printed?


d = {'a': 1, 'b': 2, 'c': 3}
for key, value in [Link]():
print(f"{key} -> {value}")
✔ Answer: a -> 1 b -> 2 c -> 3
■ Explanation: [Link]() returns key-value pairs as tuples. Tuple unpacking (key, value) extracts each. Order
preserved in Python 3.7+.

Q109. Predict the output:


lst = [5, 3, 8, 1, 9, 2]
print(sorted(lst))
print(lst)
print(sorted(lst, reverse=True))

✔ Answer: [1, 2, 3, 5, 8, 9] [5, 3, 8, 1, 9, 2] [9, 8, 5, 3, 2, 1]


■ Explanation: sorted() returns NEW sorted list; original unchanged. [Link]() modifies in-place. Both accept
reverse=True.

Q110. What is the output?


t = (10, 20, 30)
t = t + (40,)
print(t)
print([Link](20))
print([Link](30))
✔ Answer: (10, 20, 30, 40) 1 2
■ Explanation: Tuples are immutable, but concatenation creates new tuple. (40,) is a 1-element tuple (note
comma). count()=occurrences, index()=position.

Section B – Error Identification & Correction


Q111. Identify the error:
t = (1, 2, 3)
t[0] = 10

✔ Answer: TypeError: 'tuple' object does not support item assignment


■ Explanation: Tuples are immutable — cannot change elements. To 'modify', create new: t = (10,) + t[1:].
Use a list if you need mutability.

Q112. Fix the dictionary key error:


student = {'name': 'Bob', 'age': 20}
print(student['grade']) # Error

✔ Answer: Use: [Link]('grade', 'Not found') — safely returns default if key missing.
■ Explanation: Accessing a missing key raises KeyError. get(key, default) is safe. Alternatively: if 'grade' in
student: print(student['grade'])

Q113. Identify the error type:


lst = [1, 2, 3]
print(lst[5])

✔ Answer: IndexError: list index out of range


■ Explanation: lst has indices 0,1,2. Accessing index 5 is out of range. Check len(lst) or use try-except
IndexError.

Q114. [Logical Error] Find and fix:


# Intended: remove all occurrences of 3 from list
lst = [3, 1, 3, 2, 3]
for item in lst:
if item == 3:
[Link](item)
print(lst) # Expected: [1, 2]

✔ Answer: Output is [1, 3, 2] — logical error! Fix: use list comprehension: lst = [x for x in lst if x !=
3]
■ Explanation: Modifying a list while iterating skips elements. List comprehension creates new filtered list —
the correct approach.

Q115. Fix the dictionary update code:


inventory = {'apple': 10, 'banana': 5}
inventory['orange'] # should add with count 8

✔ Answer: inventory['orange'] = 8 OR [Link]({'orange': 8})


■ Explanation: Accessing a non-existent key raises KeyError. To add: assign value. inventory['orange']=8
adds if missing, updates if present.

Section C – Programming Problems


Q116. [Real-Life] Shopping cart: use a list to add/remove items and display total count.
cart = []
while True:
action = input("add/remove/view/quit: ").lower()
if action == 'add':
item = input("Item: ")
[Link](item)
print(f"Added. Cart: {cart}")
elif action == 'remove':
item = input("Item to remove: ")
if item in cart:
[Link](item)
else:
print("Item not in cart")
elif action == 'view':
print(f"Cart ({len(cart)} items): {cart}")
elif action == 'quit':
break
■ Explanation: append() adds, remove() deletes first occurrence, 'in' checks membership. len() gives count.
Real e-commerce cart logic!

Q117. Write a function to find the second largest number in a list.


def second_largest(lst):
unique = list(set(lst)) # remove duplicates
if len(unique) < 2:
return None
[Link](reverse=True)
return unique[1]

numbers = [10, 5, 20, 8, 20, 15]


print(second_largest(numbers)) # 15
■ Explanation: set() removes duplicates. sort(reverse=True) orders descending. [1] is the second element.
Handle edge case of <2 unique values.

Q118. [Case-Based] Phone book: use dict to store, search, update, delete contacts.
phonebook = {}

def add_contact(name, number):


phonebook[name] = number

def search(name):
return [Link](name, "Not found")

def delete(name):
if name in phonebook:
del phonebook[name]
return f"{name} deleted"
return "Contact not found"

add_contact("Alice", "9876543210")
add_contact("Bob", "1234567890")
print(search("Alice"))
print(delete("Bob"))
print(phonebook)
■ Explanation: Dictionary as database: name=key, number=value. get() for safe search. del for deletion. 'in'
for existence check.

Q119. Predict the output:


lst = list(range(1, 11))
squares = [x**2 for x in lst if x % 2 == 0]
print(squares)

✔ Answer: [4, 16, 36, 64, 100]


■ Explanation: List comprehension with filter: [expression for item in iterable if condition]. Even numbers
2,4,6,8,10 → squared.

Q120. [Real-Life] Student report: dict with name, marks list, compute average and grade.
students = [
{'name': 'Alice', 'marks': [85, 90, 78, 92]},
{'name': 'Bob', 'marks': [60, 55, 70, 65]},
]
for s in students:
avg = sum(s['marks']) / len(s['marks'])
grade = 'A' if avg >= 80 else 'B' if avg >= 60 else 'C'
print(f"{s['name']}: Avg={avg:.1f}, Grade={grade}")
■ Explanation: List of dicts is a common data structure (like a table). sum()/len() computes average. Nested
ternary assigns grade.

Q121. What is the output?


d = {}
words = "the cat sat on the mat the cat".split()
for w in words:
d[w] = [Link](w, 0) + 1
print(sorted([Link](), key=lambda x: x[1], reverse=True))

✔ Answer: [('the', 3), ('cat', 2), ('sat', 1), ('on', 1), ('mat', 1)]
■ Explanation: Word frequency count using [Link](). sorted with key=lambda sorts by count (index 1 of
tuple). reverse=True for descending.

Q122. Write a program to merge two dictionaries.


d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

# Method 1: update (modifies d1)


merged1 = [Link]()
[Link](d2)
print(merged1) # d2 values override d1 for common keys

# Method 2: ** unpacking (Python 3.5+)


merged2 = {**d1, **d2}
print(merged2)

✔ Answer: {'a': 1, 'b': 3, 'c': 4} {'a': 1, 'b': 3, 'c': 4}


■ Explanation: When keys overlap, later dict's value wins. {**d1,**d2} is Pythonic merge. d2 overrides d1's 'b':
2 with 'b': 3.

Q123. [Predict] Tuple packing and unpacking:


# Packing
point = 3, 4

# Unpacking
x, y = point
print(x, y)

# Swap using tuples


a, b = 10, 20
a, b = b, a
print(a, b)

✔ Answer: 3 4 20 10
■ Explanation: Tuple packing: 3,4 creates (3,4). Unpacking: x,y=point extracts values. Swap: Python
evaluates RHS first, so no temp var needed!

Q124. [Real-Life] Inventory system: track items with quantity using dict, restock if < 5.
inventory = {'apple': 10, 'banana': 3, 'orange': 7, 'grape': 2}

low_stock = []
for item, qty in [Link]():
if qty < 5:
low_stock.append(item)
inventory[item] += 20 # restock

print("Restocked:", low_stock)
print("Updated inventory:", inventory)
■ Explanation: Traverse dict with items(). Collect low-stock items. Update quantity in-place (dicts are
mutable). Real warehouse management!

Q125. Remove duplicate elements from a list while preserving order.


lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
seen = []
unique = []
for x in lst:
if x not in seen:
[Link](x)
[Link](x)
print(unique)

# Pythonic way:
unique2 = list([Link](lst))
print(unique2)

✔ Answer: [3, 1, 4, 5, 9, 2, 6] [3, 1, 4, 5, 9, 2, 6]


■ Explanation: [Link]() keeps insertion order and removes duplicates (keys are unique). list() converts
back. Elegant one-liner!

Q126. [Error] Fix the list pop error:


lst = [1, 2, 3]
[Link](5) # Error

✔ Answer: IndexError: pop index out of range. Fix: check len first or use [Link]() without index
(removes last).
■ Explanation: pop(index) removes and returns element at index. Without index, removes last. Always
validate index < len(lst).

Q127. [Case-Based] A voting system: use dict to count votes, find winner.
votes = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob', 'Alice']
tally = {}
for vote in votes:
tally[vote] = [Link](vote, 0) + 1

print("Vote tally:", tally)


winner = max(tally, key=[Link])
print("Winner:", winner)
■ Explanation: max() with key=[Link] finds the key with maximum value. This is a classic pattern for finding
the most frequent item.

Q128. What is the output of list operations?


lst = [1, 2, 3, 4, 5]
print([Link]())
print([Link](0))
print(lst)

✔ Answer: 5 1 [2, 3, 4]
■ Explanation: pop() removes and returns last element (5). pop(0) removes and returns first (1). Remaining:
[2,3,4].

Q129. [Real-Life] Stack implementation using list (browser back button simulation).
history = []

def visit(url):
[Link](url)
print(f"Visited: {url}")

def go_back():
if len(history) > 1:
[Link]()
print(f"Back to: {history[-1]}")
else:
print("No previous page")

visit("[Link]")
visit("[Link]")
visit("[Link]")
go_back()
go_back()
■ Explanation: Stack = LIFO (Last In, First Out). append() pushes, pop() removes last (most recent).
history[-1] peeks at top.

Q130. Predict the output:


matrix = [[1,2,3],[4,5,6],[7,8,9]]
for row in matrix:
for val in row:
print(val, end=' ')
print()

✔ Answer: 1 2 3 4 5 6 7 8 9
■ Explanation: 2D list (matrix): outer loop iterates rows, inner loop iterates values. print() at end of row adds
newline.

Q131. Write a program to flatten a nested list [[1,2],[3,4],[5]] → [1,2,3,4,5].


nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
print(flat)

✔ Answer: [1, 2, 3, 4, 5]
■ Explanation: Nested list comprehension: outer for iterates sublists, inner for iterates items. Equivalent to
nested loops but concise.

Q132. [Case-Based] Frequency analysis: count how many students scored in each grade
range.
marks = [85, 72, 91, 60, 78, 88, 55, 95, 67, 82]
buckets = {'A(90-100)': 0, 'B(80-89)': 0, 'C(70-79)': 0, 'D(60-69)': 0, 'F(<60)': 0}

for m in marks:
if m >= 90: buckets['A(90-100)'] += 1
elif m >= 80: buckets['B(80-89)'] += 1
elif m >= 70: buckets['C(70-79)'] += 1
elif m >= 60: buckets['D(60-69)'] += 1
else: buckets['F(<60)'] += 1

for grade, count in [Link]():


print(f"{grade}: {'*' * count} ({count})")
■ Explanation: Histogram using dict. Each mark updates its bucket. Printing '*'*count gives visual bar chart.
Real grade distribution analysis!

Q133. What is the output?


a = (1, 2, 3)
b = (4, 5, 6)
c = a + b
print(c)
print(c[2:5])

✔ Answer: (1, 2, 3, 4, 5, 6) (3, 4, 5)


■ Explanation: Tuples support concatenation with + creating new tuple. Slicing works same as lists. c[2:5] =
(3, 4, 5).

Q134. [Real-Life] Group students by their first letter of name using dict.
names = ["Alice","Bob","Anna","Charlie","Brian","Carl"]
groups = {}
for name in names:
key = name[0]
if key not in groups:
groups[key] = []
groups[key].append(name)

for letter, group in sorted([Link]()):


print(f"{letter}: {group}")
■ Explanation: Grouping by key is a fundamental dict pattern. name[0] extracts first letter. sorted()
alphabetizes output.

Q135. Predict the output of dictionary comprehension:


squares = {x: x**2 for x in range(1, 6)}
print(squares)
even_squares = {k: v for k, v in [Link]() if k % 2 == 0}
print(even_squares)

✔ Answer: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} {2: 4, 4: 16}


■ Explanation: Dict comprehension: {key: value for item in iterable}. Filter with if. Second filters only even
keys from first dict.

Q136. [Error] Fix:


lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
if lst[i] == 3:
del lst[i] # causes IndexError

✔ Answer: Use list comprehension: lst = [x for x in lst if x != 3]. Never delete from list while
iterating by index.
■ Explanation: Deleting during forward iteration shifts indices causing skip or IndexError. List comprehension
is the safe, Pythonic fix.

Q137. Write a program to find common elements between two lists.


list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

# Method 1: list comprehension


common = [x for x in list1 if x in list2]
print(common)

# Method 2: using sets (faster for large lists)


common2 = list(set(list1) & set(list2))
print(sorted(common2))

✔ Answer: [3, 4, 5] [3, 4, 5]


■ Explanation: Set intersection (&) finds common elements efficiently. O(n) vs O(n^2) for list approach.
sorted() ensures consistent order.

Q138. [Case-Based] Library book tracker using dict of lists.


library = {
'Fiction': ['Harry Potter', '1984'],
'Science': ['A Brief History', 'Cosmos'],
}

# Add a book
library['Fiction'].append('The Alchemist')
# Search
def find_book(title):
for genre, books in [Link]():
if title in books:
return f"Found in {genre}"
return "Not found"

print(find_book('Cosmos'))
print(find_book('Lord of the Rings'))
■ Explanation: Dict of lists: genre=key, list of books=value. Nested data structure. Search iterates genres and
checks membership.

Q139. What is the output?


lst = [10, 20, 30, 40, 50]
print([Link](30))
print(30 in lst)
print(60 in lst)
[Link]([60, 70])
print(lst)

✔ Answer: 2 True False [10, 20, 30, 40, 50, 60, 70]
■ Explanation: index(30) finds value 30 at index 2. 'in' operator checks membership. extend() adds all
elements of iterable to end.

Q140. [Real-Life] Contact manager: store name, phone, email in list of dicts.
contacts = []

def add_contact(name, phone, email):


[Link]({'name': name, 'phone': phone, 'email': email})

def search_contact(name):
for c in contacts:
if c['name'].lower() == [Link]():
return c
return None

add_contact("Alice", "9876543210", "alice@[Link]")


add_contact("Bob", "1234567890", "bob@[Link]")

result = search_contact("alice")
if result:
print(f"Phone: {result['phone']}, Email: {result['email']}")
■ Explanation: List of dicts is a common pattern for structured records (like database rows). Case-insensitive
search using .lower().

Q141. Predict the output:


d = {'x': 10, 'y': 20, 'z': 30}
[Link]('y')
print(d)
[Link]({'w': 40, 'x': 100})
print(d)
✔ Answer: {'x': 10, 'z': 30} {'x': 100, 'z': 30, 'w': 40}
■ Explanation: pop('y') removes key 'y'. update() adds new keys and overwrites existing ones ('x' changes
from 10 to 100).

Q142. Write a program to transpose a matrix (swap rows and columns).


matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

# Transpose using zip


transposed = [list(row) for row in zip(*matrix)]
for row in transposed:
print(row)

✔ Answer: [1, 4, 7] [2, 5, 8] [3, 6, 9]


■ Explanation: zip(*matrix) unpacks matrix rows and zips them column-wise. *matrix passes each row as
separate argument. Elegant transpose!

Q143. [Predict] enumerate() with list:


fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")

✔ Answer: 1. apple 2. banana 3. cherry


■ Explanation: enumerate(iterable, start) provides index+value pairs. start=1 begins numbering at 1. Avoids
manual counter variable.

Q144. [Real-Life] Cashier system: items and prices in dict, compute bill with discount.
menu = {'burger': 120, 'fries': 60, 'cola': 40, 'pizza': 200}
order = ['burger', 'fries', 'cola', 'pizza', 'fries']

total = 0
print("Order Summary:")
for item in set(order): # unique items
qty = [Link](item)
price = [Link](item, 0)
subtotal = qty * price
print(f" {item} x{qty} = Rs.{subtotal}")
total += subtotal

discount = 0.1 if total > 300 else 0


final = total - total * discount
print(f"Subtotal: Rs.{total}")
print(f"Discount: {discount*100:.0f}%")
print(f"Total: Rs.{final:.2f}")
■ Explanation: set(order) gets unique items. count() tallies quantity. [Link]() safely retrieves price. Real
POS (Point of Sale) system logic!

Q145. Predict the output:


lst = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, lst))
print(result)
evens = list(filter(lambda x: x % 2 == 0, lst))
print(evens)

✔ Answer: [2, 4, 6, 8, 10] [2, 4]


■ Explanation: map() applies function to each element. filter() keeps elements where function returns True.
Both return iterators; list() converts.

Q146. [Error] Identify the error type and fix:


d = {'a': 1, 'b': 2}
for key in d:
d[key + '_new'] = d[key] * 2 # RuntimeError

✔ Answer: RuntimeError: dictionary changed size during iteration. Fix: iterate over list([Link]()) or
build new dict separately.
■ Explanation: Cannot add keys while iterating a dict. Fix: new_d = {k+'_new': v*2 for k,v in [Link]()};
[Link](new_d)

Q147. Write a program to find the intersection, union, and difference of two sets.
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}

print("Union:", A | B)
print("Intersection:", A & B)
print("Difference A-B:", A - B)
print("Difference B-A:", B - A)
print("Symmetric Diff:", A ^ B)

✔ Answer: Union: {1,2,3,4,5,6,7} Intersection: {3,4,5} Difference A-B: {1,2} Difference B-A: {6,7}
Symmetric Diff: {1,2,6,7}
■ Explanation: Set operators: | union, & intersection, - difference, ^ symmetric difference (in either but not
both). Very useful for data analysis!

Q148. [Case-Based] Use a queue (list) to simulate a help desk ticket system.
queue = []

def submit_ticket(ticket):
[Link](ticket)
print(f"Ticket submitted: {ticket}")

def resolve_next():
if queue:
ticket = [Link](0)
print(f"Resolving: {ticket}")
else:
print("No tickets")

submit_ticket("WiFi down")
submit_ticket("Printer error")
submit_ticket("Login failed")
resolve_next()
resolve_next()
■ Explanation: Queue = FIFO (First In, First Out). append() enqueues, pop(0) dequeues. Note: pop(0) is
O(n); for efficiency use [Link].
Q149. What is the output?
t = (3, 1, 4, 1, 5, 9, 2, 6)
print(max(t))
print(min(t))
print(sum(t))
print([Link](1))
lst = list(t)
[Link]()
print(lst)

✔ Answer: 9 1 31 2 [1, 1, 2, 3, 4, 5, 6, 9]
■ Explanation: max/min/sum work on tuples. count(1) = 2 (two 1s). To sort, must convert to list (tuples are
immutable).

Q150. [Real-Life] Student marks tracker: use dict to store marks, compute rank.
marks = {
'Alice': 89, 'Bob': 75, 'Charlie': 92,
'Diana': 88, 'Eve': 95
}

# Sort by marks descending


ranked = sorted([Link](), key=lambda x: x[1], reverse=True)

print("Rank | Name | Marks")


print("-" * 30)
for rank, (name, mark) in enumerate(ranked, 1):
print(f" {rank} | {name:<8} | {mark}")
■ Explanation: sorted() with key=lambda sorts dict items by value. enumerate gives rank. f-string formatting
aligns columns. Real leaderboard!
TOPIC 4: Functions, OOP, Recursion, Program Design

Section A – Predict the Output


Q151. Predict the output:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet(greeting="Hey", name="Charlie"))

✔ Answer: Hello, Alice! Hi, Bob! Hey, Charlie!


■ Explanation: Default argument: greeting='Hello' used if not provided. Keyword arguments can be passed in
any order by naming them.

Q152. What is the output?


def add(a, b):
return a + b

def multiply(a, b):


return a * b

def apply(func, x, y):


return func(x, y)

print(apply(add, 3, 4))
print(apply(multiply, 3, 4))

✔ Answer: 7 12
■ Explanation: Functions are first-class objects in Python — they can be passed as arguments. 'apply' is a
higher-order function.

Q153. Predict the output:


def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment

c = counter()
print(c())
print(c())
print(c())

✔ Answer: 1 2 3
■ Explanation: Closure: inner function retains access to outer's 'count'. nonlocal allows modifying outer
variable. c() increments and returns count each call.

Q154. What is the output?


def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5))
print(factorial(0))

✔ Answer: 120 1
■ Explanation: Recursive factorial: 5! = 5*4*3*2*1 = 120. Base case: 0! = 1! = 1. Each call reduces n by 1 until
base case.

Q155. Predict the output:


class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
return "..."

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"

animals = [Dog("Rex"), Cat("Whiskers"), Dog("Buddy")]


for a in animals:
print([Link]())

✔ Answer: Rex says Woof! Whiskers says Meow! Buddy says Woof!
■ Explanation: Polymorphism: each object's speak() is called based on its actual class. The same loop
handles different types — core OOP principle!

Q156. What is the output?


def *args_demo(*args):
print(type(args))
print(args)
print(sum(args))

args_demo(1, 2, 3, 4, 5)

✔ Answer: (1, 2, 3, 4, 5) 15
■ Explanation: *args collects any number of positional arguments into a tuple. Useful when the number of
arguments is unknown.

Q157. Predict the output:


class BankAccount:
def __init__(self, owner, balance=0):
[Link] = owner
self.__balance = balance # private

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

acc = BankAccount("Alice", 1000)


[Link](500)
print(acc.get_balance())
print(acc.__balance) # What happens?

✔ Answer: 1500 AttributeError: 'BankAccount' object has no attribute '__balance'


■ Explanation: __balance is name-mangled to _BankAccount__balance (private). Direct access raises
AttributeError. Use getter method. This is encapsulation!

Q158. What is the output?


def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)

for i in range(8):
print(fibonacci(i), end=' ')

✔ Answer: 0 1 1 2 3 5 8 13
■ Explanation: Recursive Fibonacci: fib(n)=fib(n-1)+fib(n-2). Base: fib(0)=0, fib(1)=1. Sequence:
0,1,1,2,3,5,8,13...

Q159. Predict the output:


class Shape:
def area(self):
return 0

class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h

class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r ** 2

shapes = [Rectangle(4, 5), Circle(3)]


for s in shapes:
print(f"Area: {[Link]():.2f}")

✔ Answer: Area: 20.00 Area: 28.26


■ Explanation: Inheritance + Polymorphism: Rectangle and Circle override area(). Same loop works for all
shapes. OOP power!

Q160. What is the output?


def scope_demo():
x = 10 # local
print(x)

x = 100 # global
scope_demo()
print(x)

✔ Answer: 10 100
■ Explanation: Local x=10 inside function shadows global x=100. Each has own scope. Global x unchanged
after function call.

Section B – Error Identification


Q161. Identify the error:
def add(a, b):
result = a + b

print(add(3, 4))

✔ Answer: Output: None — Missing return statement!


■ Explanation: Functions without explicit return statement return None. Fix: add 'return result' or 'return a + b'
before the function ends.

Q162. What error and why?


def greet(name):
print(f"Hello, {name}!")

result = greet("Alice")
print([Link]())

✔ Answer: AttributeError: 'NoneType' object has no attribute 'upper'


■ Explanation: greet() prints but returns None. Calling .upper() on None fails. Fix: return the string instead of
printing, or don't chain methods.

Q163. Identify the error in this class:


class Student:
def __init__(name, age): # Error
[Link] = name
[Link] = age

✔ Answer: TypeError: missing 'self' as first parameter. Fix: def __init__(self, name, age):
■ Explanation: Every method must have 'self' as first parameter — it refers to the instance. Without it, 'name'
gets 'self' value at runtime.

Q164. [Recursion Error] What's wrong?


def countdown(n):
print(n)
countdown(n - 1) # No base case!

countdown(5)

✔ Answer: RecursionError: maximum recursion depth exceeded. Fix: add base case: if n <= 0:
return
■ Explanation: Every recursive function MUST have a base case to stop recursion. Without it, infinite
recursion hits Python's default limit (~1000 calls).

Q165. Fix the OOP error:


class Counter:
count = 0

def increment(self):
Count += 1 # Error

✔ Answer: NameError: 'Count' not defined. Fix: [Link] += 1 OR [Link] += 1


■ Explanation: To access instance attribute: [Link]. To access class attribute: [Link] or
self.__class__.count. Case matters ('Count' vs 'count').

Section C – Programming Problems


Q166. [Real-Life] Write a function to validate a phone number (exactly 10 digits).
def validate_phone(phone):
phone = str(phone).strip()
if [Link]() and len(phone) == 10:
return True, "Valid phone number"
return False, f"Invalid: must be exactly 10 digits, got {len(phone)}"

numbers = ["9876543210", "123456", "abc1234567", "1234567890"]


for num in numbers:
valid, msg = validate_phone(num)
print(f"{num}: {msg}")
■ Explanation: isdigit() checks all chars are digits. len() checks count. Return tuple (valid, message) for
informative feedback.

Q167. [Case-Based] Design a Student class with attributes and methods.


class Student:
school = "ABC High School" # class attribute

def __init__(self, name, roll, marks):


[Link] = name
[Link] = roll
[Link] = marks # list of marks

def average(self):
return sum([Link]) / len([Link])

def grade(self):
avg = [Link]()
if avg >= 90: return 'A'
elif avg >= 75: return 'B'
elif avg >= 60: return 'C'
else: return 'F'

def __str__(self):
return f"{[Link]} (Roll: {[Link]}) - Grade: {[Link]()}"

s1 = Student("Alice", 1, [88, 92, 85, 90])


s2 = Student("Bob", 2, [60, 55, 70, 65])
print(s1)
print(s2)
print(f"School: {[Link]}")
■ Explanation: Class attribute shared by all instances. __init__ initializes instance. __str__ controls print()
output. Methods compute derived data.

Q168. Write a recursive function to compute the sum of a list.


def list_sum(lst):
if len(lst) == 0:
return 0
return lst[0] + list_sum(lst[1:])

numbers = [1, 2, 3, 4, 5]
print(list_sum(numbers)) # 15
■ Explanation: Base case: empty list → 0. Recursive case: first element + sum of rest. lst[1:] creates sublist
without first element.

Q169. [Real-Life] Calculator: use functions with *args to accept any number of operands.
def add(*args):
return sum(args)

def multiply(*args):
result = 1
for n in args:
result *= n
return result

def calculate(operation, *numbers):


ops = {'add': add, 'multiply': multiply}
if operation in ops:
return ops[operation](*numbers)
return "Unknown operation"

print(calculate('add', 1, 2, 3, 4, 5))
print(calculate('multiply', 2, 3, 4))

✔ Answer: 15 24
■ Explanation: *args allows variable arguments. Dict maps operation names to functions. calculate()
dispatches to correct function dynamically.

Q170. Write a recursive function to reverse a string.


def reverse_string(s):
if len(s) <= 1:
return s
return reverse_string(s[1:]) + s[0]

print(reverse_string("Hello")) # olleH
print(reverse_string("Python")) # nohtyP
■ Explanation: Base case: string of length ≤1. Recursive case: reverse of rest + first character. Builds
reversed string on call stack.
Q171. [Case-Based] Bank Account class with deposit, withdraw, and overdraft protection.
class BankAccount:
def __init__(self, owner, balance=0):
[Link] = owner
self.__balance = balance
self.__transactions = []

def deposit(self, amount):


if amount > 0:
self.__balance += amount
self.__transactions.append(f"+{amount}")
return f"Deposited Rs.{amount}. Balance: Rs.{self.__balance}"
return "Invalid amount"

def withdraw(self, amount):


if amount > self.__balance:
return "Insufficient funds!"
self.__balance -= amount
self.__transactions.append(f"-{amount}")
return f"Withdrew Rs.{amount}. Balance: Rs.{self.__balance}"

def statement(self):
print(f"Account: {[Link]}")
print(f"Transactions: {', '.join(self.__transactions)}")
print(f"Balance: Rs.{self.__balance}")

acc = BankAccount("Alice", 5000)


print([Link](2000))
print([Link](1000))
print([Link](10000))
[Link]()
■ Explanation: Encapsulation: __balance is private. Only methods can access it. Overdraft check prevents
negative balance. Transaction history log.

Q172. [Predict] Lambda and sorted:


students = [
("Alice", 85), ("Bob", 92), ("Charlie", 78)
]
[Link](key=lambda x: x[1], reverse=True)
for name, mark in students:
print(f"{name}: {mark}")

✔ Answer: Bob: 92 Alice: 85 Charlie: 78


■ Explanation: lambda x: x[1] extracts the mark (index 1) for comparison. reverse=True gives descending
order. Lambda as sort key is very common.

Q173. Write a recursive function to find GCD of two numbers.


def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)

print(gcd(48, 18)) # 6
print(gcd(100, 75)) # 25
■ Explanation: Euclidean algorithm: gcd(a,b) = gcd(b, a%b). Base case: when b=0, return a.
gcd(48,18)→gcd(18,12)→gcd(12,6)→gcd(6,0)=6.

Q174. [Real-Life] Design a Library class with books collection.


class Library:
def __init__(self, name):
[Link] = name
self.__books = {} # title: available copies

def add_book(self, title, copies=1):


self.__books[title] = self.__books.get(title, 0) + copies

def borrow(self, title):


if self.__books.get(title, 0) > 0:
self.__books[title] -= 1
return f"Borrowed: {title}"
return f"Not available: {title}"

def return_book(self, title):


if title in self.__books:
self.__books[title] += 1
return f"Returned: {title}"
return "Book not in system"

def show_catalog(self):
for title, copies in self.__books.items():
status = "Available" if copies > 0 else "Not Available"
print(f" {title}: {copies} copies ({status})")

lib = Library("City Library")


lib.add_book("Python 101", 3)
lib.add_book("Data Structures", 2)
print([Link]("Python 101"))
print([Link]("Python 101"))
lib.show_catalog()
■ Explanation: Real library system with encapsulated book inventory. Methods provide controlled access.
Borrow decrements, return increments copies.

Q175. [Recursion] Write a function to check if a string is a palindrome recursively.


def is_palindrome(s):
s = [Link]().replace(' ', '')
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])

print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
print(is_palindrome("A man a plan a canal Panama")) # True
■ Explanation: Compare first and last chars. If same, recurse on inner substring s[1:-1]. Base: length ≤1 =
palindrome. Clean with lower() and strip spaces.

Q176. [Error] Fix the inheritance error:


class Animal:
def __init__(self, name):
[Link] = name

class Dog(Animal):
def __init__(self, name, breed):
# forgot super().__init__(name)
[Link] = breed

d = Dog("Rex", "Labrador")
print([Link]) # AttributeError

✔ Answer: Add super().__init__(name) in Dog.__init__: super().__init__(name) before [Link] =


breed
■ Explanation: super().__init__() calls parent class constructor. Without it, [Link] is never set. Always call
super().__init__() in child class.

Q177. [Case-Based] Temperature converter class with static method.


class Temperature:
def __init__(self, celsius):
[Link] = celsius

@staticmethod
def c_to_f(c):
return (c * 9/5) + 32

@staticmethod
def f_to_c(f):
return (f - 32) * 5/9

def display(self):
f = Temperature.c_to_f([Link])
print(f"{[Link]}C = {f:.1f}F")

t = Temperature(100)
[Link]()
print(Temperature.c_to_f(0))
print(Temperature.f_to_c(98.6))

✔ Answer: 100C = 212.0F 32.0 37.0


■ Explanation: @staticmethod: no self/cls needed; utility method. Can be called on class or instance. Perfect
for pure conversion functions.

Q178. Write a recursive binary search function.


def binary_search(lst, target, low=0, high=None):
if high is None:
high = len(lst) - 1
if low > high:
return -1
mid = (low + high) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
return binary_search(lst, target, mid+1, high)
else:
return binary_search(lst, target, low, mid-1)

nums = [1, 3, 5, 7, 9, 11, 13, 15]


print(binary_search(nums, 7)) # 3
print(binary_search(nums, 6)) # -1
■ Explanation: Divide and conquer: check middle, recurse on left or right half. O(log n) — far faster than linear
search for sorted lists.

Q179. [Real-Life] Design an Employee class with inheritance for Manager.


class Employee:
def __init__(self, name, emp_id, salary):
[Link] = name
self.emp_id = emp_id
[Link] = salary

def annual_salary(self):
return [Link] * 12

def __str__(self):
return f"Employee: {[Link]} | ID: {self.emp_id} | Monthly: Rs.{[Link]
}"

class Manager(Employee):
def __init__(self, name, emp_id, salary, team_size):
super().__init__(name, emp_id, salary)
self.team_size = team_size
[Link] = salary * 0.20

def annual_salary(self):
return super().annual_salary() + [Link] * 12

def __str__(self):
return super().__str__() + f" | Team: {self.team_size}"

emp = Employee("Alice", "E001", 30000)


mgr = Manager("Bob", "M001", 60000, 8)
print(emp)
print(f"Annual: Rs.{emp.annual_salary()}")
print(mgr)
print(f"Annual (with bonus): Rs.{mgr.annual_salary()}")
■ Explanation: Inheritance: Manager extends Employee. super() calls parent methods. Manager overrides
annual_salary() to add bonus. __str__ extends parent's.

Q180. Predict the output:


class MyClass:
class_var = 0
def __init__(self):
MyClass.class_var += 1
self.instance_var = MyClass.class_var

a = MyClass()
b = MyClass()
c = MyClass()
print(a.instance_var, b.instance_var, c.instance_var)
print(MyClass.class_var)

✔ Answer: 1 2 3 3
■ Explanation: class_var is shared. Each instance creation increments it. instance_var captures its value at
creation time. Class var = 3 after 3 instances.

Q181. Write recursive power function x^n without using **.


def power(x, n):
if n == 0:
return 1
if n < 0:
return 1 / power(x, -n)
return x * power(x, n - 1)

print(power(2, 10)) # 1024


print(power(3, 0)) # 1
print(power(2, -3)) # 0.125
■ Explanation: Base case: x^0=1. Negative exponent: 1/x^(-n). Recursive: x * x^(n-1). Handles all integer
exponents including negative.

Q182. [Case-Based] OOP: Design a simple Quiz application class.


class Quiz:
def __init__(self):
[Link] = []
[Link] = 0

def add_question(self, question, options, answer):


[Link]({
'q': question, 'opts': options, 'ans': answer
})

def run(self):
for i, q in enumerate([Link], 1):
print(f"Q{i}: {q['q']}")
for j, opt in enumerate(q['opts'], 1):
print(f" {j}. {opt}")
choice = int(input("Your answer (1-4): "))
if q['opts'][choice-1] == q['ans']:
print("Correct!")
[Link] += 1
else:
print(f"Wrong! Answer: {q['ans']}")
print(f"\nScore: {[Link]}/{len([Link])}")

quiz = Quiz()
quiz.add_question("Capital of France?",
["Berlin","London","Paris","Madrid"], "Paris")
quiz.add_question("2 + 2 = ?",
["3","4","5","6"], "4")
[Link]()
■ Explanation: OOP encapsulates state (questions, score) and behavior (add_question, run). List of dicts
stores structured quiz data. Clean design!

Q183. [Predict] Mutable default argument pitfall:


def append_to(element, lst=[]):
[Link](element)
return lst

print(append_to(1))
print(append_to(2))
print(append_to(3))

✔ Answer: [1] [1, 2] [1, 2, 3]


■ Explanation: GOTCHA: default mutable argument [] is created ONCE and reused! Fix: def
append_to(element, lst=None): if lst is None: lst = []

Q184. Write a function decorator that measures execution time.


import time

def timer(func):
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"{func.__name__} took {end-start:.4f} seconds")
return result
return wrapper

@timer
def slow_sum(n):
return sum(range(n))

result = slow_sum(1000000)
print(f"Result: {result}")
■ Explanation: Decorator = function that wraps another. @timer applies decorator. wrapper() adds timing
before/after calling original. *args/**kwargs pass all arguments through.

Q185. [Real-Life] Recursive Tower of Hanoi.


def hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1: {source} -> {target}")
return
hanoi(n-1, source, auxiliary, target)
print(f"Move disk {n}: {source} -> {target}")
hanoi(n-1, auxiliary, target, source)

hanoi(3, 'A', 'C', 'B')


■ Explanation: Classic recursion: move n-1 disks to aux, move largest to target, move n-1 from aux to target.
3 disks = 7 moves (2^n - 1).

Q186. Predict the output:


def outer(x):
def inner(y):
return x + y
return inner

add5 = outer(5)
add10 = outer(10)
print(add5(3))
print(add10(3))
print(add5(add10(2)))

✔ Answer: 8 13 17
■ Explanation: Closure: inner() captures x from outer(). add5=outer(5) creates function adding 5. add10 adds
10. add5(add10(2))=add5(12)=17.

Q187. [Case-Based] Vehicle class hierarchy for a transport company.


class Vehicle:
def __init__(self, make, model, year):
[Link] = make
[Link] = model
[Link] = year

def info(self):
return f"{[Link]} {[Link]} {[Link]}"

class Car(Vehicle):
def __init__(self, make, model, year, doors):
super().__init__(make, model, year)
[Link] = doors

def info(self):
return super().info() + f" ({[Link]}-door car)"

class Truck(Vehicle):
def __init__(self, make, model, year, payload):
super().__init__(make, model, year)
[Link] = payload

def info(self):
return super().info() + f" (payload: {[Link]}T)"

fleet = [Car("Toyota","Camry",2023,4), Truck("Volvo","FH16",2022,20)]


for v in fleet:
print([Link]())

✔ Answer: 2023 Toyota Camry (4-door car) 2022 Volvo FH16 (payload: 20T)
■ Explanation: Inheritance hierarchy: Car and Truck extend Vehicle. super().info() reuses parent.
Polymorphism: same loop, different info() output.

Q188. Write a function to check if a number is prime using a helper function.


def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

def primes_up_to(limit):
return [n for n in range(2, limit+1) if is_prime(n)]

print(primes_up_to(30))

✔ Answer: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]


■ Explanation: Helper function is_prime() hides complexity. primes_up_to() uses list comprehension +
is_prime(). sqrt optimization: only check to sqrt(n).

Q189. [Predict] __str__ vs __repr__:


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __str__(self):
return f"Point({self.x}, {self.y})"

def __repr__(self):
return f"Point(x={self.x}, y={self.y})"

p = Point(3, 4)
print(str(p))
print(repr(p))
print(p)

✔ Answer: Point(3, 4) Point(x=3, y=4) Point(3, 4)


■ Explanation: __str__ = user-friendly string (print uses it). __repr__ = developer/debug string. print() calls
__str__. repr() calls __repr__.

Q190. [Real-Life] Shopping Cart class with OOP.


class ShoppingCart:
def __init__(self):
self.__items = {}

def add_item(self, name, price, qty=1):


if name in self.__items:
self.__items[name]['qty'] += qty
else:
self.__items[name] = {'price': price, 'qty': qty}

def remove_item(self, name):


if name in self.__items:
del self.__items[name]

def total(self):
return sum(v['price'] * v['qty'] for v in self.__items.values())
def receipt(self):
print("=== RECEIPT ===")
for name, info in self.__items.items():
print(f"{name}: Rs.{info['price']} x {info['qty']} = Rs.{info['price']*in
fo['qty']}")
print(f"TOTAL: Rs.{[Link]():.2f}")

cart = ShoppingCart()
cart.add_item("Apple", 10, 3)
cart.add_item("Bread", 45)
cart.add_item("Apple", 10, 2) # adds to existing
[Link]()
■ Explanation: Encapsulated __items dict. add_item() handles both new and existing items. receipt() displays
formatted bill. Real e-commerce cart!

Q191. Predict the output of this class method:


class MathUtils:
@staticmethod
def is_even(n):
return n % 2 == 0

@classmethod
def from_string(cls, s):
return cls()

print(MathUtils.is_even(4))
print(MathUtils.is_even(7))

✔ Answer: True False


■ Explanation: @staticmethod: no self/cls. Pure utility method. Called on class directly. @classmethod
receives cls (the class). Both called without instantiation.

Q192. [Recursion] Tower of numbers: print 1 to n recursively, then n to 1.


def print_pattern(n, current=1):
if current > n:
return
print(current, end=' ')
print_pattern(n, current + 1)
print(current, end=' ')

print_pattern(4)

✔ Answer: 1 2 3 4 4 3 2 1
■ Explanation: Print before recursing (ascending), then print after returning (descending). The call stack
naturally reverses order on return!

Q193. [Case-Based] Design a simple ATM class.


class ATM:
def __init__(self, pin, balance):
self.__pin = pin
self.__balance = balance
self.__locked = False
self.__attempts = 0

def authenticate(self, pin):


if self.__locked:
return "Account locked!"
if pin == self.__pin:
self.__attempts = 0
return "Authenticated"
self.__attempts += 1
if self.__attempts >= 3:
self.__locked = True
return "Account locked after 3 failed attempts!"
return f"Wrong PIN. {3-self.__attempts} attempts left."

def withdraw(self, pin, amount):


auth = [Link](pin)
if auth != "Authenticated":
return auth
if amount > self.__balance:
return "Insufficient funds"
self.__balance -= amount
return f"Dispensed Rs.{amount}. Balance: Rs.{self.__balance}"

atm = ATM(1234, 10000)


print([Link](9999))
print([Link](1234, 2000))
■ Explanation: Complete ATM simulation: encapsulated PIN and balance, lockout after 3 failures, balance
check before withdrawal. Real security design!

Q194. [Predict] Recursive countdown:


def countdown(n):
if n <= 0:
print("Blast off!")
return
print(n)
countdown(n - 1)

countdown(5)

✔ Answer: 5 4 3 2 1 Blast off!


■ Explanation: Simple recursion: print n, recurse with n-1. Base case: n<=0 prints 'Blast off!' and returns.
Each call reduces n by 1.

Q195. [Real-Life] Create a Student Grade Book using OOP.


class GradeBook:
def __init__(self):
self.__records = {}

def add_student(self, name):


self.__records[name] = []

def add_grade(self, name, subject, grade):


if name in self.__records:
self.__records[name].append((subject, grade))

def report(self, name):


if name not in self.__records:
return "Student not found"
grades = self.__records[name]
if not grades:
return f"{name}: No grades"
avg = sum(g for _, g in grades) / len(grades)
print(f"--- Report for {name} ---")
for subject, grade in grades:
print(f" {subject}: {grade}")
print(f" Average: {avg:.1f}")

gb = GradeBook()
gb.add_student("Alice")
gb.add_grade("Alice", "Math", 92)
gb.add_grade("Alice", "Science", 88)
gb.add_grade("Alice", "English", 95)
[Link]("Alice")
■ Explanation: GradeBook encapsulates student records. Dict maps name to list of (subject,grade) tuples.
report() computes and displays formatted summary.

Q196. What is the output of this __add__ override?


class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


return Vector(self.x + other.x, self.y + other.y)

def __str__(self):
return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3)

✔ Answer: Vector(4, 6)
■ Explanation: Operator overloading: __add__ defines + behavior for objects. v1+v2 calls v1.__add__(v2).
Creates new Vector with summed components.

Q197. [Error Correction] Fix the recursive function:


def sum_digits(n):
if n < 10:
return n
return n % 10 + sum_digits(n // 10)

# What's wrong with:


def bad_power(base, exp):
return base * bad_power(base, exp) # Missing base case!
✔ Answer: bad_power has no base case — infinite recursion. Fix: if exp == 0: return 1; if exp < 0:
return 1/bad_power(base,-exp)
■ Explanation: Every recursive function needs: (1) base case to stop, (2) recursive case moving toward base
case. Missing either = infinite recursion.

Q198. [Case-Based] Polymorphism: payment system with different payment methods.


class Payment:
def pay(self, amount):
raise NotImplementedError

class CashPayment(Payment):
def pay(self, amount):
return f"Paid Rs.{amount} in cash"

class CardPayment(Payment):
def __init__(self, card_no):
self.card_no = card_no[-4:] # store only last 4 digits

def pay(self, amount):


return f"Charged Rs.{amount} to card ****{self.card_no}"

class UPIPayment(Payment):
def __init__(self, upi_id):
self.upi_id = upi_id

def pay(self, amount):


return f"Rs.{amount} transferred via UPI to {self.upi_id}"

# Polymorphic usage
payments = [
CashPayment(),
CardPayment("1234567890123456"),
UPIPayment("alice@upi")
]
for method in payments:
print([Link](500))
■ Explanation: Abstract interface: Payment defines pay() contract. Each subclass implements differently.
Same loop calls correct pay() — pure polymorphism!

Q199. Write a program using a function to generate n rows of Pascal's Triangle.


def pascals_triangle(n):
triangle = []
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
[Link](row)
return triangle

for row in pascals_triangle(6):


print(' '.join(str(x) for x in row).center(20))
■ Explanation: Each row starts and ends with 1. Middle elements = sum of two elements above.
triangle[i-1][j-1]+triangle[i-1][j] computes this.
Q200. [Real-Life] Final Project: Student Management System using full OOP.
class Student:
def __init__(self, sid, name, marks):
[Link] = sid
[Link] = name
[Link] = marks

def average(self):
return sum([Link]) / len([Link])

def grade(self):
avg = [Link]()
return 'A' if avg>=90 else 'B' if avg>=75 else 'C' if avg>=60 else 'F'

def __str__(self):
return f"[{[Link]}] {[Link]} | Avg: {[Link]():.1f} | Grade: {self.
grade()}"

class StudentManagement:
def __init__(self):
self.__students = {}

def add(self, student):


self.__students[[Link]] = student
print(f"Added: {[Link]}")

def search(self, sid):


return self.__students.get(sid, None)

def top_student(self):
return max(self.__students.values(), key=lambda s: [Link]())

def report(self):
print("\n=== STUDENT REPORT ===")
for s in sorted(self.__students.values(), key=lambda s: [Link](), reverse=
True):
print(s)
print(f"Top Student: {self.top_student().name}")

sms = StudentManagement()
[Link](Student("S001", "Alice", [92, 88, 95, 90]))
[Link](Student("S002", "Bob", [70, 65, 75, 68]))
[Link](Student("S003", "Charlie",[85, 90, 88, 92]))
[Link]()
■ Explanation: Complete system: Student class handles individual data. StudentManagement encapsulates
collection. max() with lambda finds top. Sorted report by average.
END OF QUESTION BANK

Good luck with your exam! Practice each question thoroughly and understand the
concepts, not just the answers.

You might also like