Python Question Bank
Python Question Bank
■ Python Programming
Comprehensive Question Bank
■ Topics 10
■ Questions 120
■ Easy 40
■ Medium 40
■ Hard 40
1 Variables
2 Variable Scope
3 Operators
4 Operator Precedence
5 Conditional / Branching
7 Functions
8 Lists
9 Tuples
10 Recursion
Topic 1 Variables
■ Easy Questions
Questi What is a variable in Python? Declare three variables: one storing an integer, one storing a float,
on: and one storing a string. Print all three.
Hint: A variable is a named memory location. Use = for assignment. Python is dynamically typed — no need to
declare type explicitly.
Answe
r:
A variable is a container that stores data values. Python auto-detects the type.
age = 21 # integer
Questi Which of the following is a valid Python variable name? (a) 2name (b) my_name (c) my-name (d)
on: class
Hint: Variable names must start with a letter or underscore, cannot contain hyphens, and cannot be Python
reserved keywords.
Answe
r:
Answer: (b) my_name Reason: Starts with a letter, uses only alphanumeric characters and underscores. - 2name:
starts with a digit (invalid) - my-name: contains a hyphen (invalid) - class: reserved keyword (invalid)
Questi Write a Python program that takes bytes as input from the user and converts it to Megabytes (MB)
on: and Gigabytes (GB). Display both results.
Answe
r:
mb = b / (1024 ** 2)
gb = b / (1024 ** 3)
Questi True or False: In Python, you can assign multiple variables in a single line. Give an example to
on: support your answer.
Answe
r:
TRUE. Python allows multiple assignment in a single line.
print(a, b, c) # Output: 0 0 0
■ Medium Questions
Questi Write a Python program that swaps the values of two variables WITHOUT using a third
on: (temporary) variable. Show the values before and after swapping.
Answe
r:
a, b = b, a
Questi The following code has errors. Identify and fix all bugs: 1name = "Zara" age = 22 print("Name: " +
on: name + " Age: " + age)
Hint: Check for invalid variable name and type mismatch in string concatenation.
Answe
r:
Bug 1: 1name is invalid (starts with a digit). Fix: name = "Zara" Bug 2: Cannot concatenate str with int. Fix: convert
age using str()
name = "Zara"
age = 22
Questi Write a program that takes ECAT marks (out of 400), Intermediate Part 1 marks (out of 1100), and
on: Matric marks (out of 1100), then calculates the aggregate using: ECAT 33%, Intermediate 50%,
Matric 17%.
Answe
r:
Questi What will be the output of the following code? Explain each step: x = 5 y = x x = x + 10 print(x, y)
on:
Hint: Integers in Python are immutable. Assigning y = x copies the value, not the reference.
Answe
r:
Output: 15 5 Step-by-step: x = 5 -> x stores 5 y = x -> y gets a COPY of 5 (not a reference to x) x = x+10 -> x
becomes 15; y is unaffected Result: x=15, y=5
Questi Explain Python's integer interning concept and demonstrate using id() that two variables assigned
on: the same small integer (100) share memory, while two variables assigned a large integer (1000)
may not.
Hint: Python interns (caches) integers from -5 to 256. id(var) returns the memory address of the object.
Answe
r:
a = 100; b = 100
print(f"id(a)={id(a)}, id(b)={id(b)}")
c = 1000; d = 1000
print(f"id(c)={id(c)}, id(d)={id(d)}")
Explanation: Python caches small integers (-5 to 256) for efficiency. Large integers get new objects each time they
are created.
Questi Write a program that accepts a temperature in Celsius and converts it to Fahrenheit, Kelvin, and
on: Rankine. Store each in a separate variable and display results to 2 decimal places.
Answe
r:
Questi Write a program that converts kilometers to meters, centimeters, miles, and nautical miles
on: simultaneously. Use descriptive variable names and format output neatly.
Answe
r:
meters = km * 1000
centimeters = km * 100000
miles = km * 0.621371
nautical_miles = km * 0.539957
print(f"{km} km =")
Questi What is the difference between == and is when comparing variables? Write a program showing a
on: case where == returns True but is returns False, and explain why.
Answe
r:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
list1 and list2 have equal content but are distinct objects. list3 = list1 creates an alias — both names point to the
exact same object, so is returns True.
■ Easy Questions
Questi What are the four types of variable scope in Python? List and briefly describe each.
on:
Answe
r:
L — Local: Variables defined inside a function; only accessible there. E — Enclosing: Variables in the outer
function's scope (for nested functions). G — Global: Variables defined at module level; accessible everywhere in
the module. B — Built-in: Names pre-defined by Python, e.g. len, print, range.
Questi Write a program that demonstrates the difference between a local and a global variable by using
on: the same variable name inside and outside a function.
Hint: A variable inside a function is local by default and does not affect the global variable with the same name.
Answe
r:
x = "I am global"
def show():
x = "I am local"
show()
# Output:
# I am local
# I am global
Questi True or False: A variable declared inside a function can be accessed outside the function in
on: Python (without using global).
Answe
r:
FALSE. Local variables exist only within the function scope. Accessing them outside raises NameError.
def func():
local_var = 10
func()
Questi What will be the output of the following code? count = 100 def display(): print(count) display()
on: print(count)
Hint: If a variable is not assigned inside a function, Python looks for it in the enclosing/global scope (LEGB rule).
Answe
r:
Output: 100 100 Explanation: count is not assigned inside display(), so Python looks up to the global scope and
finds count = 100. Both calls print 100.
■ Medium Questions
Questi Write a program that uses the global keyword to modify a global variable from inside a function.
on: Show the value before and after the function call.
Hint: Use 'global variable_name' at the top of the function before modifying it.
Answe
r:
balance = 1000
def deposit(amount):
global balance
balance += amount
print(f"Before: {balance}")
deposit(500)
print(f"After: {balance}")
# Output:
# Before: 1000
# After: 1500
Questi Find and fix the error: total = 0 def add_to_total(n): total = total + n add_to_total(50) print(total)
on:
Hint: Python sees total on the right side of = inside the function, so it treats total as local — causing
UnboundLocalError.
Answe
r:
Fix: Add 'global total' inside the function.
total = 0
def add_to_total(n):
global total
total = total + n
add_to_total(50)
print(total) # Output: 50
Questi Demonstrate enclosing scope in Python by writing a nested function where the inner function
on: reads a variable defined in the outer function.
Hint: The inner function can read variables from the outer function scope without any keyword.
Answe
r:
def outer():
def inner():
inner()
outer()
Questi What is the nonlocal keyword in Python? Write a program using it to modify a variable from an
on: enclosing (non-global) scope.
Answe
r:
def counter():
count = 0
def increment():
nonlocal count
count += 1
print(f"Count: {count}")
increment()
increment()
increment()
counter()
Questi Trace the following code and predict output. Explain the LEGB lookup for each print: x = "global"
on: def outer(): x = "enclosing" def inner(): x = "local" print(x) inner() print(x) outer() print(x)
Hint: Each function creates its own scope. Follow LEGB at each print statement.
Answe
r:
Output: local enclosing global - inner(): x = "local" found in Local scope. - outer() after inner(): x = "enclosing" in
outer's Local scope. - Top-level print: x = "global" from Global scope.
Questi Write a simple bank account program using global scope for balance. Provide three functions:
on: deposit(amount), withdraw(amount), and check_balance(). Ensure withdrawals do not exceed the
balance.
Hint: All three functions must use 'global balance' to read/modify the shared state.
Answe
r:
balance = 0.0
def deposit(amount):
global balance
balance += amount
def withdraw(amount):
global balance
print("Insufficient funds!")
else:
balance -= amount
def check_balance():
deposit(500)
withdraw(100)
check_balance()
Questi What happens when a variable is used BEFORE it is assigned inside a function that also assigns
on: it later? Demonstrate with code and explain the error.
Hint: Python pre-scans function bodies. If a name appears on the left side of = anywhere in the function, Python
treats it as local everywhere in that function.
Answe
r:
value = 50
def problematic():
value = 100 # Python marks value as local for the ENTIRE function
def fixed():
global value
print(value) # 50
value = 100
print(value) # 100
fixed()
Questi Using closures, write a function make_multiplier(n) that returns an inner function. The inner
on: function multiplies any given number by n. Demonstrate by creating triple and quintuple functions.
Hint: This is a closure: the inner function closes over the enclosing variable n.
Answe
r:
def make_multiplier(n):
def multiplier(x):
return multiplier
triple = make_multiplier(3)
quintuple = make_multiplier(5)
print(triple(7)) # 21
print(quintuple(4)) # 20
print(triple(10)) # 30
Topic 3 Operators
■ Easy Questions
Questi List the five main categories of operators in Python with one example each.
on:
Answe
r:
1. Arithmetic: +, -, *, /, //, %, ** e.g. 5 + 3 = 8 2. Comparison: ==, !=, <, >, <=, >= e.g. 5 > 3 -> True 3. Logical: and,
or, not e.g. True and False -> False 4. Assignment: =, +=, -=, *= e.g. x += 5 5. Bitwise: &, |, ^, ~, <<, >> e.g. 5 & 3 =
1
Questi Write a program that accepts two integers and displays: sum, difference, product, float division,
on: integer division, remainder, and power.
Answe
r:
print(f"Sum: {a + b}")
print(f"Difference: {a - b}")
print(f"Product: {a * b}")
print(f"Remainder: {a % b}")
Questi What is the output of the following code? x = 17 print(x % 5) print(x // 5) print(x ** 2)
on:
Answe
r:
Output: 2 3 289 17 % 5 = 2 (17 = 5x3 + 2) 17 // 5 = 3 (floor division) 17 ** 2 = 289
Questi True or False: In Python, / always returns a float, even when dividing two integers that divide
on: evenly.
Answe
r:
TRUE. In Python 3, / always produces a float.
print(10 // 2) # 5 (integer)
■ Medium Questions
Questi Write a program that determines the nature of roots of the quadratic equation ax^2 + bx + c = 0 by
on: computing the discriminant D = b^2 - 4ac, and then calculates the actual roots.
Hint: D = b^2 - 4ac. D==0: real equal; D>0: real distinct; D<0: imaginary. Roots: x = (-b +/- sqrt(D)) / 2a
Answe
r:
import math
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
D = b**2 - 4*a*c
if D == 0:
x = -b / (2*a)
elif D > 0:
else:
real = -b / (2*a)
Questi Explain and demonstrate all augmented assignment operators in Python. Start with x = 10 and
on: apply +=, -=, *=, /=, //=, %=, **= sequentially, printing x after each step.
Answe
r:
x = 10
Questi What are comparison operators in Python? Write a program that reads two numbers and prints
on: the result of all six comparison operations between them.
Hint: The six comparison operators: ==, !=, <, >, <=, >=. They return True or False.
Answe
r:
a = float(input("Enter a: "))
b = float(input("Enter b: "))
Questi Write a Python program that uses logical operators (and, or, not) to check if a given year is a leap
on: year.
Hint: Leap year condition: (divisible by 4 AND NOT divisible by 100) OR (divisible by 400).
Answe
r:
else:
Questi Explain bitwise operators in Python (&, |, ^, ~, <<, >>). Demonstrate each using integers 12 and
on: 10. Explain binary-level computation for & and |.
Hint: 12 = 1100 in binary. 10 = 1010 in binary. & (AND): both bits must be 1 -> 1000 = 8 | (OR): either bit is 1 ->
1110 = 14
Answe
r:
a, b = 12, 10
Questi Write a program that converts a binary number (input as a string) to its decimal equivalent using
on: ONLY arithmetic operators (do not use int(x, 2)).
Answe
r:
decimal = 0
Questi Using ONLY modulo (%) and integer division (//) operators, write a program that extracts every
on: individual digit of a positive integer entered by the user.
Hint: Repeatedly use n % 10 to get the last digit, and n // 10 to remove it.
Answe
r:
digits = []
temp = n
[Link](temp % 10)
temp //= 10
Questi Python has identity operators (is, is not) and membership operators (in, not in). Write a program
on: demonstrating all four with appropriate examples and explain what each tests.
Hint: is tests object identity (same memory object). in tests if a value exists in a sequence.
Answe
r:
# Identity operators
# Membership operators
■ Easy Questions
Questi What is operator precedence? List at least 6 levels of Python operator precedence from highest to
on: lowest.
Answe
r:
Operator precedence determines the order in which operations are evaluated. Highest to lowest (selected levels):
1. () -- Parentheses 2. ** -- Exponentiation 3. +x, -x -- Unary 4. *, /, //, % 5. +, - 6. Comparison: ==, !=, <, >, <=, >=
7. not 8. and 9. or -- (lowest)
Questi Evaluate the following expression step by step without running it, then verify: result = 2 + 3 * 4 - 6 /
on: 2
Hint: Multiplication and division are performed before addition and subtraction.
Answe
r:
Step 1: 3 * 4 = 12 Step 2: 6 / 2 = 3.0 Step 3: 2 + 12 - 3.0 = 11.0 result = 11.0
Answe
r:
FALSE. ** is right-associative, so: 2 ** 3 ** 2 = 2 ** (3**2) = 2 ** 9 = 512 NOT: (2**3) ** 2 = 64
Answe
r:
Output: 11 5 10 - 2 + 3 = 8 + 3 = 11 (left to right) 10 - (2+3) = 10 - 5 = 5 (parentheses first)
■ Medium Questions
Questi Evaluate each expression and explain the order of operations: a = 5 + 2 ** 3 * 4 // 6 - 1 b = not 5 >
on: 3 and 10 != 10 or True
Hint: For a: ** first, then *, then //, then +, then -. For b: comparisons first, then not, then and, then or.
Answe
r:
Expression a: 2**3 = 8 -> 8*4 = 32 -> 32//6 = 5 -> 5+5-1 = 9 a = 9 Expression b: 5>3 = True -> not True = False
10!=10 = False -> False and False = False False or True = True b = True
Questi Write a Python program that computes the distance between two points (x1,y1) and (x2,y2) using
on: the distance formula. Be careful to correctly parenthesize the expression.
Answe
r:
import math
x1 = float(input("x1: "))
y1 = float(input("y1: "))
x2 = float(input("x2: "))
y2 = float(input("y2: "))
print(f"Distance = {d:.4f}")
Questi Without parentheses, what does this evaluate to? 4 + 5 * 2 > 10 and not 3 == 3 Trace through all
on: precedence levels.
Answe
r:
Step-by-step: 5 * 2 = 10 4 + 10 = 14 14 > 10 = True 3 == 3 = True not True = False True and False = False Result:
False
Questi Write a Python program that calculates compound interest. Ensure operator precedence is
on: correctly applied.
Answe
r:
t = int(input("Years: "))
A = P * (1 + r / n) ** (n * t)
CI = A - P
Questi Evaluate the following without running it. Show ALL intermediate steps: result = 3 + 4 * 2 ** 2 - 10
on: % 3 + (6 // 2) * 2
Answe
r:
Step 1: (6 // 2) = 3 Step 2: 2 ** 2 = 4 Step 3: 4 * 4 = 16 Step 4: 10 % 3 = 1 Step 5: 3 * 2 = 6 (the (6//2)*2) Step 6: 3 +
16 - 1 + 6 = 24 result = 24
Questi Explain short-circuit evaluation in Python for 'and' and 'or'. How does operator precedence interact
on: with short-circuiting?
Hint: and returns first falsy value or last value. or returns first truthy value or last value.
Answe
r:
x = 0
print(result) # 0
y = 5
print(result) # 5
# = False or True
# = True
Questi Write a Python program that computes BMI and displays the category. Ensure all arithmetic uses
on: correct precedence.
Hint: BMI = weight(kg) / height(m)^2 <18.5: Underweight | 18.5-24.9: Normal | 25-29.9: Overweight | >=30:
Obese
Answe
r:
print(f"BMI: {bmi:.2f}")
else: print("Obese")
Questi What is operator associativity and how does it differ from operator precedence? Demonstrate
on: left-associativity of - and right-associativity of **.
Hint: Most operators: left-associative (a-b-c = (a-b)-c). **: right-associative (a**b**c = a**(b**c)).
Answe
r:
# Left-associativity of subtraction
print(20 - 5 - 3) # (20-5)-3 = 12
# Right-associativity of **
print((2 ** 3) ** 2) # 64
Precedence: which operator binds tighter (e.g. * before +). Associativity: direction when two operators have SAME
precedence.
■ Easy Questions
Questi What is an if-elif-else statement? Write a program that takes an integer and prints whether it is
on: positive, negative, or zero.
Hint: Use if, elif, else blocks. Each block executes based on whether its condition is True.
Answe
r:
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Questi Write a program that takes a point (x, y) from the user and determines which quadrant of the
on: Cartesian plane it lies in, or if it is on an axis.
Hint: Q1: x>0,y>0 | Q2: x<0,y>0 | Q3: x<0,y<0 | Q4: x>0,y<0 On axis: x==0 or y==0
Answe
r:
x = float(input("x: "))
y = float(input("y: "))
if x == 0 and y == 0:
print("Origin")
elif x == 0:
print("On Y-axis")
elif y == 0:
print("On X-axis")
print("Quadrant I")
print("Quadrant II")
print("Quadrant III")
else:
print("Quadrant IV")
Questi True or False: In Python, if blocks require curly braces {} to define the block body.
on:
Answe
r:
FALSE. Python uses INDENTATION (typically 4 spaces) to define code blocks. No curly braces are needed.
if 5 > 3:
Questi Write a program that checks whether a given number is even or odd AND also prints whether it is
on: divisible by 5.
Answe
r:
if n % 5 == 0:
else:
■ Medium Questions
Questi Write a program to check whether a given number is a palindrome (reads the same forwards and
on: backwards).
Hint: Convert the number to a string and compare it with its reverse: str(n) == str(n)[::-1]
Answe
r:
if n == n[::-1]:
print(f"{n} is a Palindrome")
else:
Questi Write a program that takes marks (0-100) and prints the letter grade and GPA on a 4.0 scale:
on: A(>=90, 4.0), B(>=80, 3.0), C(>=70, 2.0), D(>=60, 1.0), F(<60, 0.0).
Answe
r:
Questi Write a program that takes three sides of a triangle, checks if it is valid, then classifies it as
on: Equilateral, Isosceles, or Scalene.
Hint: Valid: sum of any two sides > third. Equilateral: all equal. Isosceles: two equal. Scalene: all different.
Answe
r:
a = float(input("Side a: "))
b = float(input("Side b: "))
c = float(input("Side c: "))
if a == b == c:
print("Equilateral")
print("Isosceles")
else:
print("Scalene")
else:
Questi Write a program using nested if that takes a username and password and grants access only if
on: both are correct (admin / 1234). Display specific messages for wrong username, wrong password,
and success.
Hint: First check username. Inside that block, check password (nested if).
Answe
r:
if username == "admin":
if password == "1234":
else:
print("Wrong password.")
else:
Questi Write a program that takes coefficients a, b, c of ax^2+bx+c=0, determines the nature of roots, and
on: computes/displays the actual roots (real or complex).
Hint: D = b^2 - 4ac D>0: two real roots | D=0: one root | D<0: complex roots
Answe
r:
import math
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
D = b**2 - 4*a*c
if D > 0:
elif D == 0:
else:
real = -b/(2*a)
imag = [Link](-D)/(2*a)
Questi Write a simple calculator accepting two numbers and an operator (+,-,*,/,//,%,**). Handle division
on: by zero and invalid operators gracefully.
Hint: Use if-elif to branch on the operator. Check b==0 before any division.
Answe
r:
op = input("Operator: ")
if op == "+": print(a + b)
else: print(a % b)
Questi Write a single-guess number guessing program using only if-elif-else (no loops). Store a secret
on: number, take one guess, tell the user correct/too high/too low, and how far off they were.
Answe
r:
secret = 42
if guess == secret:
print("Correct!")
else:
Questi Write a program using ternary (conditional) expressions in at least three scenarios: (1) max of two
on: numbers, (2) even or odd, (3) Pass or Fail for score >= 50.
Answe
r:
a, b = 15, 22
print(f"Max: {maximum}")
n = 37
print(f"{n} is {parity}")
score = 45
■ Easy Questions
Questi What is the difference between a for loop and a while loop in Python? Give one example of each.
on:
Hint: for: known/finite iterations over a sequence. while: repeats based on a condition being True.
Answe
r:
for i in range(5):
x = 1
while x <= 5:
x += 1
Questi Write a Python program using a for loop that prints the multiplication table of a number entered by
on: the user (from 1 to 10).
Answe
r:
Questi Write a while loop that keeps asking the user to enter positive numbers and sums them. Stop
on: when the user enters 0 and print the total.
Answe
r:
total = 0
while True:
if num == 0:
break
total += num
Questi What does the following code print? Explain what break and continue do. for i in range(1, 8): if i ==
on: 4: continue if i == 6: break print(i)
Hint: continue skips the current iteration. break exits the loop entirely.
Answe
r:
Output: 1 2 3 5 continue skips printing 4. break exits the loop when i==6, so 6 and 7 are never printed.
■ Medium Questions
Questi Write a program that takes a range (start and end) from the user, displays all prime numbers in
on: that range, and prints their sum.
Hint: Test divisibility using range(2, int(n**0.5)+1). A prime has no divisors other than 1 and itself.
Answe
r:
primes = []
is_prime = True
if num % d == 0:
is_prime = False
break
if is_prime:
[Link](num)
print("Primes:", primes)
print("Sum:", sum(primes))
Questi Write a program using nested for loops that draws the following diamond/hourglass pattern for
on: n=4: * * * * * * * * * * * * * * * * * * *
Hint: Use two separate loops -- first decreasing, then increasing -- with range.
Answe
r:
n = 4
print("* " * i)
print("* " * i)
Questi Write a program that takes a sentence from the user and uses a for loop to count the number of
on: vowels and consonants.
Hint: Vowels: aeiouAEIOU. Skip spaces and non-alphabet characters using .isalpha().
Answe
r:
vowels = consonants = 0
for ch in sentence:
if [Link]():
if [Link]() in "aeiou":
vowels += 1
else:
consonants += 1
Questi Write a program that generates a random password using a while loop. Ask for: length, include
on: uppercase? include lowercase? include digits? include special characters? Generate accordingly.
Hint: Use [Link]() on a combined character pool built from user preferences.
Answe
r:
pool = ""
password = ""
if pool:
password += [Link](pool)
print(f"Password: {password}")
Questi Write a program using nested for loops to find all perfect numbers up to 10,000. A perfect number
on: equals the sum of its proper divisors (e.g., 6 = 1+2+3).
Hint: For each n, sum all i where n%i==0 and i<n. If sum==n, it is perfect.
Answe
r:
if divisor_sum == n:
Questi Using ONLY a while loop (no string conversion), write a program that reverses an integer and
on: checks if it is a palindrome.
Hint: Extract digits: digit = n%10. Build reversed: rev = rev*10 + digit. Remove digit: n //= 10.
Answe
r:
original, reversed_n = n, 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
print(f"Reversed: {reversed_n}")
Questi Write a prime checker using a for loop with an else clause. Explain what the else clause on a loop
on: does.
Hint: The else block of a for loop executes ONLY if the loop completed without hitting a break.
Answe
r:
if n < 2:
print("Not prime")
else:
if n % i == 0:
break
else:
print(f"{n} IS prime")
The else clause runs only if the for loop finished without executing break, meaning no divisor was found.
Questi Write a program using nested loops to print Floyd's Triangle of n rows: 1 2 3 4 5 6 7 8 9 10
on:
Hint: Use a counter that increments with each cell. Outer loop = rows; inner loop = columns.
Answe
r:
counter = 1
for j in range(i):
counter += 1
print()
Topic 7 Functions
■ Easy Questions
Questi What is a function in Python? What are the benefits of using functions? Write a simple function
on: greet(name) that prints a greeting message.
Hint: A function is a reusable block of code defined with def. Benefits: code reuse, modularity, readability.
Answe
r:
def greet(name):
greet("Ali")
greet("Sara")
Questi Write a function convert_temp(value, unit) that converts Fahrenheit to Celsius if unit='F', and
on: Celsius to Fahrenheit if unit='C'.
Answe
r:
if unit == 'F':
print(f"{value}F = {result:.2f}C")
result = value * 9 / 5 + 32
print(f"{value}C = {result:.2f}F")
else:
print("Invalid unit.")
convert_temp(100, 'C')
convert_temp(32, 'F')
Questi What are default parameters in Python? Write a function power(base, exp=2) that returns base
on: raised to exp, defaulting to squaring.
Hint: Default parameter values are assigned in the function signature with =.
Answe
r:
print(power(5)) # 25
print(power(3, 4)) # 81
Questi True or False: A Python function must always explicitly return a value using the return statement.
on:
Answe
r:
FALSE. If a function has no return statement, it returns None by default.
def say_hi():
print("Hi")
result = say_hi()
print(result) # None
■ Medium Questions
Questi Write a function calculate_gpa(subjects) that accepts a list of tuples (grade_point, credit_hours)
on: and returns the GPA. Test it with at least 4 subjects.
Answe
r:
def calculate_gpa(subjects):
gpa = calculate_gpa(courses)
print(f"GPA: {gpa:.2f}")
Questi Write a program using a lambda function to find the larger of two numbers, then pass the larger
on: number to a UDF print_table(n, limit) that prints its multiplication table up to limit.
Answe
r:
n = larger(a, b)
print_table(n, 10)
Questi Write a program using a lambda to convert a string to uppercase, then pass the result to a UDF
on: named invert(s) that returns the string in reverse order.
Answe
r:
def invert(s):
return s[::-1]
uppercased = to_upper(text)
reversed_text = invert(uppercased)
print(f"Uppercased: {uppercased}")
print(f"Reversed: {reversed_text}")
Questi Write Python functions to calculate Permutation P(n,r) and Combination C(n,r) using user-defined
on: functions. Call them from a main program.
Answe
r:
def factorial(n):
result = 1
result *= i
return result
n = int(input("n: "))
r = int(input("r: "))
print(f"P({n},{r}) = {permutation(n,r)}")
print(f"C({n},{r}) = {combination(n,r)}")
Questi Write a program using *args and **kwargs. Create a function describe_student(*subjects, **info)
on: that accepts any number of positional arguments (subjects) and keyword arguments (name, age,
gpa) and prints a formatted profile.
Hint: *args collects extra positional arguments as a tuple. **kwargs collects keyword arguments as a dict.
Answe
r:
Questi Write a memoize(func) decorator that caches results. Demonstrate by memoizing a Fibonacci
on: function and show how repeated calls skip recomputation.
Hint: Store results in a dictionary keyed by arguments. Return cached result if already computed.
Answe
r:
def memoize(func):
cache = {}
def wrapper(n):
if n not in cache:
cache[n] = func(n)
else:
return cache[n]
return wrapper
@memoize
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fibonacci(10)) # computed
print(fibonacci(20)) # computed
Questi Write a semester GPA calculator using functions. Ask for number of subjects, then grade point
on: and credit hours for each. Use separate functions: get_subjects(), compute_gpa(),
display_result().
Hint: Decompose: get_subjects() for input, compute_gpa(subjects) for calculation, display_result(gpa) for output.
Answe
r:
def get_subjects(n):
subjects = []
[Link]((gp, ch))
return subjects
def compute_gpa(subjects):
def display_result(gpa):
display_result(compute_gpa(get_subjects(n)))
Questi Write safe_divide(a, b) that handles ZeroDivisionError and TypeError. Also write a lambda
on: wrapper that pre-validates inputs are numbers before calling safe_divide.
Hint: Use try-except inside the function. Lambda checks isinstance(x, (int, float)).
Answe
r:
try:
return a / b
except ZeroDivisionError:
except TypeError:
Topic 8 Lists
■ Easy Questions
Questi What is a list in Python? How does it differ from a regular array? Create a list containing your
on: name, age, GPA, and a boolean, then print each element with its index.
Hint: Python lists are dynamic, heterogeneous, and ordered. Access elements with list[index].
Answe
r:
Key difference: Python lists can hold mixed data types. Traditional arrays (in other languages) typically hold one
data type.
Questi Create a list of 5 integers and demonstrate: appending an element, removing an element,
on: inserting at a position, and checking membership.
Answe
r:
print(nums)
Hint: 0-based indexing. Negative indices count from end. Slicing [start:stop] is exclusive of stop.
Answe
r:
Output: banana date ['banana', 'cherry']
Questi Accept 5 numbers from the user into a list and print it sorted ascending and descending without
on: modifying the original list.
Hint: Use sorted(list) to return a new sorted list without altering the original.
Answe
r:
■ Medium Questions
Questi Use list comprehension to: (1) create squares of 1-10, (2) filter even numbers from 1-20, (3) create
on: (number, square) tuple pairs for 1-5.
Answe
r:
print("Squares:", squares)
print("Evens:", evens)
print("Pairs:", pairs)
Questi Remove duplicate elements from a list while preserving the original order of first appearances,
on: WITHOUT using set() as the final result.
Hint: Iterate and add to a new list only if the element has not been seen before.
Answe
r:
original = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
seen = []
unique = []
[Link](item)
[Link](item)
print("Original:", original)
Questi Write a program that takes a 3x3 2D list (matrix) and computes its transpose (swap rows and
on: columns).
Answe
r:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
print("Original:")
print("Transpose:")
Questi Write a function flatten(nested) that takes a nested list (list of lists) and returns a single flat list
on: containing all elements.
Hint: Iterate the outer list; for each inner list, iterate its elements.
Answe
r:
def flatten(nested):
flat = []
[Link](item)
return flat
print(flatten(nested)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Questi Implement Bubble Sort on a list of integers without using any built-in sort functions. Show each
on: pass of the algorithm.
Hint: Repeatedly swap adjacent elements if in wrong order. After each pass, the largest unsorted element
bubbles to its position.
Answe
r:
def bubble_sort(arr):
n = len(arr)
return arr
print("Sorted:", bubble_sort(data))
Questi Generate a random password using a list. Guarantee at least one uppercase, one lowercase, one
on: digit, and one special character, then fill the rest randomly and shuffle.
Hint: Use [Link]() for mandatory characters. Build pool for remainder. Use [Link]().
Answe
r:
mandatory = [
[Link](string.ascii_uppercase),
[Link](string.ascii_lowercase),
[Link]([Link]),
[Link]([Link])
[Link](pwd)
print("Password:", "".join(pwd))
Questi Implement Binary Search on a sorted list. Return the index of the target element or -1 if not found.
on:
Hint: mid = (low+high)//2 If arr[mid]==target: return mid. If arr[mid]<target: search right; else search left.
Answe
r:
return -1
Questi Write a program that reads a sentence, splits it into words (a list), then: (1) sorts words
on: alphabetically, (2) counts word frequency, (3) finds the most and least frequent words.
Hint: Use .split(), a dictionary for frequency, max() and min() with key= parameter.
Answe
r:
words = [Link]()
print("Sorted:", sorted(words))
freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1
print("Frequencies:", freq)
Topic 9 Tuples
■ Easy Questions
Questi What is a tuple in Python? How is it different from a list? Create a tuple with 5 elements and
on: access its elements using indexing and slicing.
Hint: Tuples are IMMUTABLE sequences defined with (). Lists are MUTABLE and defined with [].
Answe
r:
print(coords[0]) # 10
print(coords[-1]) # 50
Key difference: Tuples are immutable -- you cannot change, add, or remove elements after creation.
Questi True or False: You can have a tuple with only one element by writing t = (5).
on:
Answe
r:
FALSE. (5) is just an integer in parentheses. A single-element tuple MUST include a trailing comma.
Questi Write a program that stores two points as tuples, calculates the distance between them, and
on: identifies which quadrant each point lies in.
Answe
r:
import math
d = [Link]((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)
print(f"Distance: {d:.4f}")
def quadrant(p):
x, y = p
Questi What will the following code output? Explain each line: t = (1, 2, 3, 2, 4, 2) print([Link](2))
on: print([Link](3)) print(len(t))
Hint: .count(x) returns how many times x appears. .index(x) returns first position of x.
Answe
r:
Output: 3 2 6 [Link](2) = 3 (2 appears at indices 1, 3, 5) [Link](3) = 2 (3 is at index 2) len(t) = 6 (6 elements)
■ Medium Questions
Questi Demonstrate tuple packing and unpacking. Pack three student attributes (name, marks, grade)
on: into a tuple, then unpack them into separate variables.
Answe
r:
# Packing
print(f"Packed: {student}")
# Unpacking
# Extended unpacking
Questi Convert a list of student records (each a tuple of name and score) into a sorted leaderboard by
on: score in descending order.
Answe
r:
students = [("Ali",78),("Sara",92),("Umar",85),("Hina",92),("Bilal",67)]
Questi When should you use a tuple instead of a list in Python? Give three concrete scenarios.
on:
Hint: Think about: immutability guarantees, dictionary keys, function return values.
Answe
r:
1. Coordinates / Constants: point = (3.14, 2.71) -- values that must not change. 2. Dictionary keys: Lists cannot be
dict keys (unhashable); Tuples can: {(0,0): "origin"} 3. Function multiple return values: return x1, x2 Returns a tuple
-- safe and lightweight. 4. Named tuples for structured records without class overhead.
Questi Write a function that accepts any number of tuples (each representing (value, weight)) and
on: computes the weighted average.
Answe
r:
def weighted_average(*data_points):
result = weighted_average((80,3),(90,4),(70,2),(85,3))
Questi Use [Link] to represent a Student with fields: name, roll, gpa. Create 3 students,
on: store in a list, and display the one with the highest GPA.
Hint: from collections import namedtuple Student = namedtuple('Student', ['name', 'roll', 'gpa'])
Answe
r:
students = [
Questi Use a tuple as a dictionary key to create a lookup table for distances between city pairs. Ask the
on: user for two cities and display the distance.
Hint: distances = {('Lahore','Karachi'): 1210, ...}. Check both orderings of the key.
Answe
r:
distances = {
c1 = input("City 1: ").strip().title()
c2 = input("City 2: ").strip().title()
Questi Take a list of 2D coordinate tuples, remove duplicates, sort by distance from the origin, and print
on: the sorted list with distances.
Hint: Distance from origin: sqrt(x^2 + y^2). Use set() for deduplication, then sort.
Answe
r:
import math
points = [(3,4),(1,1),(0,5),(3,4),(2,2),(1,1)]
unique = list(set(points))
print("Point Distance")
for p in sorted_pts:
Questi Demonstrate that tuples are hashable while lists are not. Then use this property to count the
on: frequency of each coordinate tuple in a list.
Hint: hash(tuple) works. hash(list) raises TypeError. Use tuple as dict key.
Answe
r:
print(hash(t)) # works
try:
print(hash(l)) # TypeError
except TypeError as e:
coords = [(1,2),(3,4),(1,2),(5,6),(3,4),(1,2)]
freq = {}
freq[point] = [Link](point, 0) + 1
Topic 10 Recursion
■ Easy Questions
Questi What is recursion? What are the two essential components of every recursive function? Give a
on: real-world analogy.
Answe
r:
Recursion: A function that calls itself to solve a smaller version of the same problem. Two essential components: 1.
Base case -- The condition that STOPS the recursion. 2. Recursive case -- The function calls itself with
smaller/simpler input. Analogy: Russian nesting dolls -- open each doll to find a smaller one inside, until you reach
the smallest doll (base case).
Questi Write a recursive function factorial(n) that computes n!. Show the call stack for factorial(4).
on:
Answe
r:
def factorial(n):
if n == 0: # base case
return 1
return n * factorial(n - 1)
print(factorial(4)) # 24
Call stack: factorial(4) -> 4 * factorial(3) factorial(3) -> 3 * factorial(2) factorial(2) -> 2 * factorial(1) factorial(1) -> 1 *
factorial(0) factorial(0) -> 1 Result: 1*1*2*3*4 = 24
Questi Write a recursive function sum_to_n(n) that returns the sum of all integers from 1 to n.
on:
Answe
r:
def sum_to_n(n):
if n == 1:
return 1
return n + sum_to_n(n - 1)
print(sum_to_n(10)) # 55
print(sum_to_n(100)) # 5050
Questi Trace the execution of countdown(3): def countdown(n): if n == 0: print("Blast off!") return print(n)
on: countdown(n - 1)
Hint: Follow each call in order. The function prints BEFORE the recursive call.
Answe
r:
Output: 3 2 1 Blast off! countdown(3) prints 3, calls countdown(2) countdown(2) prints 2, calls countdown(1)
countdown(1) prints 1, calls countdown(0) countdown(0) prints "Blast off!" and returns
■ Medium Questions
Questi Write a recursive function fibonacci(n). Then write it iteratively. Compare the efficiency of both
on: approaches.
Hint: Base: fib(0)=0, fib(1)=1 Recursive: fib(n)=fib(n-1)+fib(n-2) -- O(2^n) time Iterative: O(n) time
Answe
r:
def fib_recursive(n):
if n <= 1: return n
def fib_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print()
Questi Write a recursive function power(base, exp) that computes base^exp WITHOUT using the **
on: operator.
Hint: Base case: power(base, 0) = 1 Recursive case: power(base, exp) = base * power(base, exp-1)
Answe
r:
if exp == 0:
return 1
print(power(5, 0)) # 1
Hint: Base case: string of length 0 or 1 is always a palindrome. Recursive case: first char == last char AND the
middle is a palindrome.
Answe
r:
def is_palindrome(s):
s = [Link]()
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("radar")) # True
print(is_palindrome("hello")) # False
print(is_palindrome("racecar")) # True
Questi Implement recursive P(n,r) and C(n,r) using a recursive factorial helper function.
on:
Answe
r:
def factorial(n):
if n == 0: return 1
return n * factorial(n - 1)
n, r = 7, 3
print(f"C({n},{r}) = {combination(n,r)}") # 35
Questi Write a recursive function gcd(a,b) using the Euclidean algorithm. Then use it to compute the
on: LCM.
Hint: GCD: base: gcd(a,0)=a; recursive: gcd(a,b)=gcd(b, a%b) LCM: lcm(a,b) = (a*b) / gcd(a,b)
Answe
r:
if b == 0:
return a
return gcd(b, a % b)
return (a * b) // gcd(a, b)
print(gcd(48, 18)) # 6
print(lcm(12, 18)) # 36
Questi Write a recursive Python function to print all permutations of a given string.
on:
Hint: For each character, fix it at the front and recursively permute the remaining string. Base case: string of
length 1.
Answe
r:
if len(s) == 0:
print(prefix)
return
for i in range(len(s)):
permutations("ABC")
Questi Implement the Tower of Hanoi problem recursively for n disks. Print each move clearly showing
on: which peg to move from and to.
Hint: Move top (n-1) disks from source to auxiliary. Move nth disk from source to destination. Move (n-1) disks
from auxiliary to destination. Base case: n == 0.
Answe
r:
if n == 0:
return
Questi Write a recursive function flatten_recursive(nested) that flattens a deeply nested list of
on: ARBITRARY depth into a flat list.
Hint: Base case: element is not a list -> return [element]. Recursive case: element is a list -> flatten each item
recursively.
Answe
r:
def flatten_recursive(nested):
result = []
if isinstance(item, list):
[Link](flatten_recursive(item))
else:
[Link](item)
return result
print(flatten_recursive(deep))
# [1, 2, 3, 4, 5, 6, 7, 8]