0% found this document useful (0 votes)
2 views67 pages

Python Question Bank

The document is a comprehensive question bank for Python programming, covering 10 topics and containing 120 questions categorized into easy, medium, and hard levels. Each topic includes various types of questions such as conceptual, coding, debugging, and analytical. The document aims to assist learners in mastering Python concepts through practical examples and exercises.

Uploaded by

ghost.of.apsacs
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)
2 views67 pages

Python Question Bank

The document is a comprehensive question bank for Python programming, covering 10 topics and containing 120 questions categorized into easy, medium, and hard levels. Each topic includes various types of questions such as conceptual, coding, debugging, and analytical. The document aims to assist learners in mastering Python concepts through practical examples and exercises.

Uploaded by

ghost.of.apsacs
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 — Question Bank CS Lab Series

■ 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

6 Loops (for & while)

7 Functions

8 Lists

9 Tuples

10 Recursion

Page 1 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Page 2 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 1 Variables

■ Easy Questions

Q1.1 [Conceptual] EASY

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

gpa = 3.75 # float

name = "Ali" # string

print(age, gpa, name)

# Output: 21 3.75 Ali

Q1.2 [Multiple Choice] EASY

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)

Q1.3 [Code Writing] EASY

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.

Hint: MB = bytes / (1024 x 1024) | GB = bytes / (1024 x 1024 x 1024)

Answe
r:

b = float(input("Enter size in Bytes: "))

mb = b / (1024 ** 2)

gb = b / (1024 ** 3)

print(f"{b} Bytes = {mb:.4f} MB")

print(f"{b} Bytes = {gb:.6f} GB")

Page 3 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q1.4 [True/False] EASY

Questi True or False: In Python, you can assign multiple variables in a single line. Give an example to
on: support your answer.

Hint: Python supports multiple assignment using commas on one line.

Answe
r:
TRUE. Python allows multiple assignment in a single line.

x, y, z = 10, 20.5, "Hello"

print(x, y, z) # Output: 10 20.5 Hello

a = b = c = 0 # All three assigned the same value

print(a, b, c) # Output: 0 0 0

■ Medium Questions

Q1.5 [Code Writing] MEDIUM

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.

Hint: Python allows tuple unpacking: a, b = b, a

Answe
r:

a = int(input("Enter value of a: "))

b = int(input("Enter value of b: "))

print(f"Before swap: a = {a}, b = {b}")

a, b = b, a

print(f"After swap: a = {a}, b = {b}")

Q1.6 [Debugging] MEDIUM

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

print("Name: " + name + " Age: " + str(age))

Page 4 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q1.7 [Code Writing] MEDIUM

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%.

Hint: Aggregate = (ECAT/400 x 33) + (Inter/1100 x 50) + (Matric/1100 x 17)

Answe
r:

ecat = float(input("ECAT Marks (out of 400): "))

inter = float(input("Intermediate Marks (out of 1100): "))

matric = float(input("Matric Marks (out of 1100): "))

aggregate = (ecat/400 * 33) + (inter/1100 * 50) + (matric/1100 * 17)

print(f"Your Aggregate: {aggregate:.2f}%")

Q1.8 [Analytical] MEDIUM

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

■ Hard (Advanced) Questions

Q1.9 [Code Writing + Analytical] HARD

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)}")

print(f"Same object? {a is b}") # True -- interned

c = 1000; d = 1000

print(f"id(c)={id(c)}, id(d)={id(d)}")

print(f"Same object? {c is d}") # May be False -- not interned

Explanation: Python caches small integers (-5 to 256) for efficiency. Large integers get new objects each time they
are created.

Page 5 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q1.10 [Code Writing] HARD

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.

Hint: F = (C x 9/5) + 32 | K = C + 273.15 | R = (C + 273.15) x 9/5

Answe
r:

celsius = float(input("Enter temperature in Celsius: "))

fahrenheit = (celsius * 9/5) + 32

kelvin = celsius + 273.15

rankine = kelvin * 9/5

print(f"Celsius: {celsius:.2f} C")

print(f"Fahrenheit: {fahrenheit:.2f} F")

print(f"Kelvin: {kelvin:.2f} K")

print(f"Rankine: {rankine:.2f} R")

Q1.11 [Code Writing] HARD

Questi Write a program that converts kilometers to meters, centimeters, miles, and nautical miles
on: simultaneously. Use descriptive variable names and format output neatly.

Hint: 1 km = 1000 m = 100,000 cm = 0.621371 miles = 0.539957 nautical miles

Answe
r:

km = float(input("Enter distance in Kilometers: "))

meters = km * 1000

centimeters = km * 100000

miles = km * 0.621371

nautical_miles = km * 0.539957

print(f"{km} km =")

print(f" {meters:,.2f} meters")

print(f" {centimeters:,.2f} centimeters")

print(f" {miles:.4f} miles")

print(f" {nautical_miles:.4f} nautical miles")

Page 6 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q1.12 [Analytical / Code Tracing] HARD

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.

Hint: == compares VALUES; is compares IDENTITY (same object in memory).

Answe
r:

list1 = [1, 2, 3]

list2 = [1, 2, 3]

print(list1 == list2) # True -- same values

print(list1 is list2) # False -- different objects in memory

list3 = list1

print(list1 is list3) # True -- both point to the same object

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.

Page 7 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 2 Variable Scope

■ Easy Questions

Q2.1 [Conceptual] EASY

Questi What are the four types of variable scope in Python? List and briefly describe each.
on:

Hint: Remember the LEGB rule: Local, Enclosing, Global, Built-in.

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.

Q2.2 [Code Writing] EASY

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"

print(x) # prints local

show()

print(x) # prints global

# Output:

# I am local

# I am global

Page 8 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q2.3 [True/False] EASY

Questi True or False: A variable declared inside a function can be accessed outside the function in
on: Python (without using global).

Hint: Think about the boundaries of local scope.

Answe
r:
FALSE. Local variables exist only within the function scope. Accessing them outside raises NameError.

def func():

local_var = 10

func()

print(local_var) # NameError: name 'local_var' is not defined

Q2.4 [Code Tracing] EASY

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

Page 9 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q2.5 [Code Writing] MEDIUM

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

Q2.6 [Debugging] MEDIUM

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

Page 10 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q2.7 [Code Writing] MEDIUM

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():

message = "Hello from outer!"

def inner():

print(message) # accesses enclosing scope

inner()

outer()

# Output: Hello from outer!

Q2.8 [Analytical] MEDIUM

Questi What is the nonlocal keyword in Python? Write a program using it to modify a variable from an
on: enclosing (non-global) scope.

Hint: nonlocal is to enclosing scope what global is to global scope.

Answe
r:

def counter():

count = 0

def increment():

nonlocal count

count += 1

print(f"Count: {count}")

increment()

increment()

increment()

counter()

# Output: Count: 1 / Count: 2 / Count: 3

■ Hard (Advanced) Questions

Page 11 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q2.9 [Code Tracing] HARD

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.

Q2.10 [Code Writing] HARD

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

print(f"Deposited: {amount:.2f} | Balance: {balance:.2f}")

def withdraw(amount):

global balance

if amount > balance:

print("Insufficient funds!")

else:

balance -= amount

print(f"Withdrawn: {amount:.2f} | Balance: {balance:.2f}")

def check_balance():

print(f"Current Balance: {balance:.2f}")

deposit(500)

withdraw(100)

check_balance()

Page 12 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q2.11 [Analytical] HARD

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():

print(value) # UnboundLocalError here!

value = 100 # Python marks value as local for the ENTIRE function

# problematic() # Raises: UnboundLocalError

def fixed():

global value

print(value) # 50

value = 100

print(value) # 100

fixed()

Page 13 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q2.12 [Code Writing] HARD

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 x * n # n captured from enclosing scope

return multiplier

triple = make_multiplier(3)

quintuple = make_multiplier(5)

print(triple(7)) # 21

print(quintuple(4)) # 20

print(triple(10)) # 30

Page 14 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 3 Operators

■ Easy Questions

Q3.1 [Conceptual] EASY

Questi List the five main categories of operators in Python with one example each.
on:

Hint: Think: arithmetic, comparison, logical, assignment, bitwise.

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

Q3.2 [Code Writing] EASY

Questi Write a program that accepts two integers and displays: sum, difference, product, float division,
on: integer division, remainder, and power.

Hint: Use +, -, *, /, //, %, ** operators.

Answe
r:

a = int(input("First number: "))

b = int(input("Second number: "))

print(f"Sum: {a + b}")

print(f"Difference: {a - b}")

print(f"Product: {a * b}")

print(f"Float Division: {a / b:.2f}")

print(f"Integer Division: {a // b}")

print(f"Remainder: {a % b}")

print(f"Power (a^b): {a ** b}")

Q3.3 [Code Tracing] EASY

Questi What is the output of the following code? x = 17 print(x % 5) print(x // 5) print(x ** 2)
on:

Hint: % is modulo (remainder), // is integer floor division, ** is exponentiation.

Answe
r:
Output: 2 3 289 17 % 5 = 2 (17 = 5x3 + 2) 17 // 5 = 3 (floor division) 17 ** 2 = 289

Page 15 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q3.4 [True/False] EASY

Questi True or False: In Python, / always returns a float, even when dividing two integers that divide
on: evenly.

Hint: Compare / (true division) with // (floor division).

Answe
r:
TRUE. In Python 3, / always produces a float.

print(10 / 2) # 5.0 (float, not 5)

print(10 // 2) # 5 (integer)

■ Medium Questions

Q3.5 [Code Writing] MEDIUM

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)

print(f"Real equal roots: x = {x}")

elif D > 0:

x1 = (-b + [Link](D)) / (2*a)

x2 = (-b - [Link](D)) / (2*a)

print(f"Real distinct roots: x1={x1:.4f}, x2={x2:.4f}")

else:

real = -b / (2*a)

imag = [Link](-D) / (2*a)

print(f"Imaginary roots: {real:.4f} +/- {imag:.4f}i")

Page 16 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q3.6 [Code Writing] MEDIUM

Questi Explain and demonstrate all augmented assignment operators in Python. Start with x = 10 and
on: apply +=, -=, *=, /=, //=, %=, **= sequentially, printing x after each step.

Hint: x += 5 is shorthand for x = x + 5.

Answe
r:

x = 10

x += 5; print(f"After +=5: {x}") # 15

x -= 3; print(f"After -=3: {x}") # 12

x *= 2; print(f"After *=2: {x}") # 24

x /= 4; print(f"After /=4: {x}") # 6.0

x //= 2; print(f"After //=2: {x}") # 3.0

x %= 2; print(f"After %=2: {x}") # 1.0

x **= 5; print(f"After **=5: {x}") # 1.0

Q3.7 [Analytical] MEDIUM

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: "))

print(f"{a} == {b} -> {a == b}")

print(f"{a} != {b} -> {a != b}")

print(f"{a} < {b} -> {a < b}")

print(f"{a} > {b} -> {a > b}")

print(f"{a} <= {b} -> {a <= b}")

print(f"{a} >= {b} -> {a >= b}")

Page 17 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q3.8 [Code Writing] MEDIUM

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:

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(f"{year} is a Leap Year")

else:

print(f"{year} is NOT a Leap Year")

■ Hard (Advanced) Questions

Q3.9 [Analytical + Code] HARD

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

print(f"a & b = {a & b}") # 8 (1100 & 1010 = 1000)

print(f"a | b = {a | b}") # 14 (1100 | 1010 = 1110)

print(f"a ^ b = {a ^ b}") # 6 (1100 ^ 1010 = 0110)

print(f"~a = {~a}") # -13

print(f"a << 1 = {a << 1}") # 24 (shift left = multiply by 2)

print(f"a >> 1 = {a >> 1}") # 6 (shift right = divide by 2)

Page 18 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q3.10 [Code Writing] HARD

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)).

Hint: Iterate each digit left to right. decimal = decimal * 2 + int(digit)

Answe
r:

binary = input("Enter a binary number: ")

decimal = 0

for digit in binary:

decimal = decimal * 2 + int(digit)

print(f"Binary {binary} = Decimal {decimal}")

# Example: "1101" -> 0->1->3->6->13

Q3.11 [Code Writing] HARD

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:

n = int(input("Enter a positive integer: "))

digits = []

temp = n

while temp > 0:

[Link](temp % 10)

temp //= 10

print("Digits (reverse):", digits)

print("Digits (original):", digits[::-1])

Page 19 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q3.12 [Analytical / Code] HARD

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

a = [1, 2, 3]; b = a; c = [1, 2, 3]

print(a is b) # True -- same object

print(a is c) # False -- equal but different objects

print(a is not c) # True

# Membership operators

fruits = ["apple", "mango", "banana"]

print("mango" in fruits) # True

print("grape" not in fruits) # True

print("apple" not in fruits) # False

Page 20 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 4 Operator Precedence

■ Easy Questions

Q4.1 [Conceptual] EASY

Questi What is operator precedence? List at least 6 levels of Python operator precedence from highest to
on: lowest.

Hint: Remember the mnemonic P-E-M-D-A-S extended for Python.

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)

Q4.2 [Code Tracing] EASY

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

Q4.3 [True/False] EASY

Questi True or False: 2 ** 3 ** 2 evaluates as (2 ** 3) ** 2 = 64 in Python.


on:

Hint: The ** operator is RIGHT-ASSOCIATIVE in Python.

Answe
r:
FALSE. ** is right-associative, so: 2 ** 3 ** 2 = 2 ** (3**2) = 2 ** 9 = 512 NOT: (2**3) ** 2 = 64

Q4.4 [Code Tracing] EASY

Questi What is the output? print(10 - 2 + 3) print(10 - (2 + 3))


on:

Hint: Parentheses override default left-to-right evaluation.

Answe
r:
Output: 11 5 10 - 2 + 3 = 8 + 3 = 11 (left to right) 10 - (2+3) = 10 - 5 = 5 (parentheses first)

■ Medium Questions

Page 21 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q4.5 [Code Tracing] MEDIUM

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

Q4.6 [Code Writing] MEDIUM

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.

Hint: d = sqrt( (x2-x1)^2 + (y2-y1)^2 ) Use ** 0.5 or [Link]()

Answe
r:

import math

x1 = float(input("x1: "))

y1 = float(input("y1: "))

x2 = float(input("x2: "))

y2 = float(input("y2: "))

d = [Link]((x2 - x1)**2 + (y2 - y1)**2)

print(f"Distance = {d:.4f}")

Q4.7 [Analytical] MEDIUM

Questi Without parentheses, what does this evaluate to? 4 + 5 * 2 > 10 and not 3 == 3 Trace through all
on: precedence levels.

Hint: Order: arithmetic -> comparison -> not -> and

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

Page 22 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q4.8 [Code Writing] MEDIUM

Questi Write a Python program that calculates compound interest. Ensure operator precedence is
on: correctly applied.

Hint: A = P * (1 + r/n) ** (n*t) CI = A - P (P=principal, r=rate decimal, n=compoundings/year, t=years)

Answe
r:

P = float(input("Principal (P): "))

r = float(input("Annual Rate (%): ")) / 100

n = int(input("Compoundings per year: "))

t = int(input("Years: "))

A = P * (1 + r / n) ** (n * t)

CI = A - P

print(f"Amount after {t} years: {A:.2f}")

print(f"Compound Interest: {CI:.2f}")

■ Hard (Advanced) Questions

Q4.9 [Code Tracing] HARD

Questi Evaluate the following without running it. Show ALL intermediate steps: result = 3 + 4 * 2 ** 2 - 10
on: % 3 + (6 // 2) * 2

Hint: Follow: parentheses -> ** -> *, //, % -> +, -

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

Page 23 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q4.10 [Analytical] HARD

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

result = x and 10/x # No ZeroDivisionError! x is falsy -> returns 0

print(result) # 0

y = 5

result = y or 10/0 # No error! y is truthy -> returns 5

print(result) # 5

# Precedence: not > and > or

# False or not False and True

# = False or (not False) and True

# = False or True

# = True

print(False or not False and True) # True

Q4.11 [Code Writing] HARD

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:

weight = float(input("Weight in kg: "))

height = float(input("Height in meters: "))

bmi = weight / height ** 2 # ** before /

print(f"BMI: {bmi:.2f}")

if bmi < 18.5: print("Underweight")

elif bmi < 25: print("Normal")

elif bmi < 30: print("Overweight")

else: print("Obese")

Page 24 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q4.12 [Analytical] HARD

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

print((20 - 5) - 3) # 12 -- confirms left-to-right

# Right-associativity of **

print(2 ** 3 ** 2) # 2**(3**2) = 2**9 = 512

print(2 ** (3 ** 2)) # 512

print((2 ** 3) ** 2) # 64

Precedence: which operator binds tighter (e.g. * before +). Associativity: direction when two operators have SAME
precedence.

Page 25 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 5 Conditional / Branching

■ Easy Questions

Q5.1 [Conceptual] EASY

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:

n = int(input("Enter a number: "))

if n > 0:

print("Positive")

elif n < 0:

print("Negative")

else:

print("Zero")

Page 26 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.2 [Code Writing] EASY

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")

elif x > 0 and y > 0:

print("Quadrant I")

elif x < 0 and y > 0:

print("Quadrant II")

elif x < 0 and y < 0:

print("Quadrant III")

else:

print("Quadrant IV")

Q5.3 [True/False] EASY

Questi True or False: In Python, if blocks require curly braces {} to define the block body.
on:

Hint: Python uses indentation, not braces.

Answe
r:
FALSE. Python uses INDENTATION (typically 4 spaces) to define code blocks. No curly braces are needed.

if 5 > 3:

print("Five is greater") # indented block

Page 27 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.4 [Code Writing] EASY

Questi Write a program that checks whether a given number is even or odd AND also prints whether it is
on: divisible by 5.

Hint: Even: n%2==0 | Divisible by 5: n%5==0

Answe
r:

n = int(input("Enter a number: "))

print("Even" if n % 2 == 0 else "Odd")

if n % 5 == 0:

print("Also divisible by 5")

else:

print("Not divisible by 5")

■ Medium Questions

Q5.5 [Code Writing] MEDIUM

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:

n = input("Enter a number: ")

if n == n[::-1]:

print(f"{n} is a Palindrome")

else:

print(f"{n} is NOT a Palindrome")

Page 28 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.6 [Code Writing] MEDIUM

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).

Hint: Use a chain of elif statements checking from highest to lowest.

Answe
r:

marks = float(input("Marks (0-100): "))

if marks >= 90: grade, gpa = "A", 4.0

elif marks >= 80: grade, gpa = "B", 3.0

elif marks >= 70: grade, gpa = "C", 2.0

elif marks >= 60: grade, gpa = "D", 1.0

else: grade, gpa = "F", 0.0

print(f"Grade: {grade} | GPA: {gpa}")

Q5.7 [Code Writing] MEDIUM

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 and a+c > b and b+c > a:

if a == b == c:

print("Equilateral")

elif a==b or b==c or a==c:

print("Isosceles")

else:

print("Scalene")

else:

print("Not a valid triangle")

Page 29 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.8 [Code Writing] MEDIUM

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:

username = input("Username: ")

password = input("Password: ")

if username == "admin":

if password == "1234":

print("Login successful! Welcome, admin.")

else:

print("Wrong password.")

else:

print("Username not found.")

■ Hard (Advanced) Questions

Page 30 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.9 [Code Writing] HARD

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:

x1 = (-b + [Link](D)) / (2*a)

x2 = (-b - [Link](D)) / (2*a)

print(f"Two real roots: x1={x1:.4f}, x2={x2:.4f}")

elif D == 0:

print(f"One real root: x = {-b/(2*a):.4f}")

else:

real = -b/(2*a)

imag = [Link](-D)/(2*a)

print(f"Complex: {real:.4f} +/- {imag:.4f}i")

Page 31 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.10 [Code Writing] HARD

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:

a = float(input("First number: "))

op = input("Operator: ")

b = float(input("Second number: "))

if op == "+": print(a + b)

elif op == "-": print(a - b)

elif op == "*": print(a * b)

elif op == "**": print(a ** b)

elif op in ("/", "//", "%"):

if b == 0: print("Error: Division by zero!")

elif op == "/": print(a / b)

elif op == "//": print(a // b)

else: print(a % b)

else: print("Invalid operator!")

Q5.11 [Code Writing] HARD

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.

Hint: Use abs() to compute absolute difference.

Answe
r:

secret = 42

guess = int(input("Guess the number (1-100): "))

diff = abs(secret - guess)

if guess == secret:

print("Correct!")

elif guess < secret:

print(f"Too low! You were {diff} away.")

else:

print(f"Too high! You were {diff} away.")

Page 32 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q5.12 [Code Writing] HARD

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.

Hint: Python ternary syntax: value_if_true if condition else value_if_false

Answe
r:

a, b = 15, 22

maximum = a if a > b else b

print(f"Max: {maximum}")

n = 37

parity = "Even" if n % 2 == 0 else "Odd"

print(f"{n} is {parity}")

score = 45

result = "Pass" if score >= 50 else "Fail"

print(f"Score {score}: {result}")

Page 33 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 6 Loops (for & while)

■ Easy Questions

Q6.1 [Conceptual] EASY

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 loop -- iterate a fixed number of times

for i in range(5):

print(i, end=" ") # 0 1 2 3 4

# while loop -- iterate based on condition

x = 1

while x <= 5:

print(x, end=" ") # 1 2 3 4 5

x += 1

Q6.2 [Code Writing] EASY

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).

Hint: Use range(1, 11) to iterate from 1 to 10 inclusive.

Answe
r:

n = int(input("Enter a number: "))

for i in range(1, 11):

print(f"{n} x {i} = {n * i}")

Page 34 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q6.3 [Code Writing] EASY

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.

Hint: Use while True with a break statement when 0 is entered.

Answe
r:

total = 0

while True:

num = float(input("Enter a number (0 to stop): "))

if num == 0:

break

total += num

print(f"Total sum: {total:.2f}")

Q6.4 [Code Tracing] EASY

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

Page 35 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q6.5 [Code Writing] MEDIUM

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:

start = int(input("Start: "))

end = int(input("End: "))

primes = []

for num in range(max(2, start), end + 1):

is_prime = True

for d in range(2, int(num**0.5) + 1):

if num % d == 0:

is_prime = False

break

if is_prime:

[Link](num)

print("Primes:", primes)

print("Sum:", sum(primes))

Q6.6 [Code Writing] MEDIUM

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

for i in range(n, 0, -1):

print("* " * i)

for i in range(2, n + 1):

print("* " * i)

Page 36 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q6.7 [Code Writing] MEDIUM

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:

sentence = input("Enter a sentence: ")

vowels = consonants = 0

for ch in sentence:

if [Link]():

if [Link]() in "aeiou":

vowels += 1

else:

consonants += 1

print(f"Vowels: {vowels} | Consonants: {consonants}")

Page 37 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q6.8 [Code Writing] MEDIUM

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:

import random, string

length = int(input("Length: "))

use_upper = input("Uppercase? (y/n): ").lower() == 'y'

use_lower = input("Lowercase? (y/n): ").lower() == 'y'

use_digits = input("Digits? (y/n): ").lower() == 'y'

use_special = input("Special chars? (y/n): ").lower() == 'y'

pool = ""

if use_upper: pool += string.ascii_uppercase

if use_lower: pool += string.ascii_lowercase

if use_digits: pool += [Link]

if use_special: pool += [Link]

password = ""

if pool:

while len(password) < length:

password += [Link](pool)

print(f"Password: {password}")

■ Hard (Advanced) Questions

Q6.9 [Code Writing] HARD

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:

for n in range(2, 10001):

divisor_sum = sum(i for i in range(1, n) if n % i == 0)

if divisor_sum == n:

print(f"{n} is a perfect number")

# Output: 6, 28, 496, 8128

Page 38 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q6.10 [Code Writing] HARD

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:

n = int(input("Enter a positive integer: "))

original, reversed_n = n, 0

while n > 0:

reversed_n = reversed_n * 10 + n % 10

n //= 10

print(f"Reversed: {reversed_n}")

print("Palindrome!" if original == reversed_n else "Not a palindrome.")

Q6.11 [Code Writing] HARD

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:

n = int(input("Enter a number: "))

if n < 2:

print("Not prime")

else:

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

print(f"{n} is NOT prime (divisible by {i})")

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.

Page 39 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q6.12 [Code Writing] HARD

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:

n = int(input("Number of rows: "))

counter = 1

for i in range(1, n + 1):

for j in range(i):

print(counter, end=" ")

counter += 1

print()

Page 40 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 7 Functions

■ Easy Questions

Q7.1 [Conceptual] EASY

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):

print(f"Hello, {name}! Welcome to Python.")

greet("Ali")

greet("Sara")

Benefits: Code reuse, easier debugging, modularity, abstraction.

Q7.2 [Code Writing] EASY

Questi Write a function convert_temp(value, unit) that converts Fahrenheit to Celsius if unit='F', and
on: Celsius to Fahrenheit if unit='C'.

Hint: C = (F-32) * 5/9 F = C * 9/5 + 32

Answe
r:

def convert_temp(value, unit):

if unit == 'F':

result = (value - 32) * 5 / 9

print(f"{value}F = {result:.2f}C")

elif unit == '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')

Page 41 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.3 [Code Writing] EASY

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:

def power(base, exp=2):

return base ** exp

print(power(5)) # 25

print(power(3, 4)) # 81

print(power(2, 10)) # 1024

Q7.4 [True/False] EASY

Questi True or False: A Python function must always explicitly return a value using the return statement.
on:

Hint: What does a function return if it has no return statement?

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

Page 42 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.5 [Code Writing] MEDIUM

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.

Hint: GPA = sum(grade_point * credit_hours) / sum(credit_hours)

Answe
r:

def calculate_gpa(subjects):

total_points = sum(gp * ch for gp, ch in subjects)

total_hours = sum(ch for gp, ch in subjects)

return total_points / total_hours

courses = [(4.0, 3), (3.0, 3), (3.5, 2), (2.0, 1)]

gpa = calculate_gpa(courses)

print(f"GPA: {gpa:.2f}")

Q7.6 [Code Writing] MEDIUM

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.

Hint: lambda a, b: a if a > b else b

Answe
r:

larger = lambda a, b: a if a > b else b

def print_table(n, limit):

for i in range(1, limit + 1):

print(f"{n} x {i} = {n * i}")

a = int(input("First number: "))

b = int(input("Second number: "))

n = larger(a, b)

print_table(n, 10)

Page 43 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.7 [Code Writing] MEDIUM

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.

Hint: lambda s: [Link]() | Reverse with s[::-1]

Answe
r:

to_upper = lambda s: [Link]()

def invert(s):

return s[::-1]

text = input("Enter a string: ")

uppercased = to_upper(text)

reversed_text = invert(uppercased)

print(f"Uppercased: {uppercased}")

print(f"Reversed: {reversed_text}")

Page 44 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.8 [Code Writing] MEDIUM

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.

Hint: P(n,r) = n! / (n-r)! C(n,r) = n! / (r! * (n-r)!)

Answe
r:

def factorial(n):

result = 1

for i in range(2, n + 1):

result *= i

return result

def permutation(n, r):

return factorial(n) // factorial(n - r)

def combination(n, r):

return factorial(n) // (factorial(r) * factorial(n - r))

n = int(input("n: "))

r = int(input("r: "))

print(f"P({n},{r}) = {permutation(n,r)}")

print(f"C({n},{r}) = {combination(n,r)}")

■ Hard (Advanced) Questions

Page 45 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.9 [Code Writing] HARD

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:

def describe_student(*subjects, **info):

print("--- Student Profile ---")

for key, val in [Link]():

print(f" {[Link]()}: {val}")

print(f" Subjects: {', '.join(subjects)}")

describe_student("Math", "Physics", "CS",

name="Ali", age=20, gpa=3.8)

Page 46 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.10 [Code Writing] HARD

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:

print(f" [Cache hit for n={n}]")

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(10)) # cache hit

print(fibonacci(20)) # computed

Page 47 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.11 [Code Writing] HARD

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 = []

for i in range(1, n+1):

gp = float(input(f"Subject {i} Grade Point: "))

ch = int(input(f"Subject {i} Credit Hours: "))

[Link]((gp, ch))

return subjects

def compute_gpa(subjects):

return sum(gp*ch for gp,ch in subjects) / sum(ch for gp,ch in subjects)

def display_result(gpa):

print(f"Semester GPA: {gpa:.2f}")

if gpa >= 3.5: print("Excellent! Dean's List.")

elif gpa >= 2.0: print("Good Standing.")

else: print("Academic Probation.")

n = int(input("Number of subjects: "))

display_result(compute_gpa(get_subjects(n)))

Page 48 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q7.12 [Code Writing] HARD

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:

def safe_divide(a, b):

try:

return a / b

except ZeroDivisionError:

return "Error: Cannot divide by zero"

except TypeError:

return "Error: Invalid types"

validate = lambda a, b: safe_divide(a, b) if isinstance(a,(int,float)) and


isinstance(b,(int,float)) else "Error: Non-numeric input"

print(validate(10, 2)) # 5.0

print(validate(10, 0)) # Error: divide by zero

print(validate("x", 2)) # Error: Non-numeric

Page 49 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 8 Lists

■ Easy Questions

Q8.1 [Conceptual] EASY

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:

profile = ["Ali", 21, 3.75, True]

for i, item in enumerate(profile):

print(f"Index {i}: {item}")

Key difference: Python lists can hold mixed data types. Traditional arrays (in other languages) typically hold one
data type.

Q8.2 [Code Writing] EASY

Questi Create a list of 5 integers and demonstrate: appending an element, removing an element,
on: inserting at a position, and checking membership.

Hint: Use .append(), .remove(), .insert(), and the in operator.

Answe
r:

nums = [10, 20, 30, 40, 50]

[Link](60) # add at end

[Link](30) # remove value 30

[Link](1, 99) # insert 99 at index 1

print(99 in nums) # True

print(nums)

Q8.3 [Code Tracing] EASY

Questi What is the output? fruits = ["apple","banana","cherry","date"] print(fruits[1]) print(fruits[-1])


on: print(fruits[1:3])

Hint: 0-based indexing. Negative indices count from end. Slicing [start:stop] is exclusive of stop.

Answe
r:
Output: banana date ['banana', 'cherry']

Page 50 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q8.4 [Code Writing] EASY

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:

nums = [int(input(f"Number {i+1}: ")) for i in range(5)]

print("Original: ", nums)

print("Ascending: ", sorted(nums))

print("Descending:", sorted(nums, reverse=True))

print("Still original:", nums)

■ Medium Questions

Q8.5 [Code Writing] MEDIUM

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.

Hint: Syntax: [expression for item in iterable if condition]

Answe
r:

squares = [x**2 for x in range(1, 11)]

print("Squares:", squares)

evens = [x for x in range(1, 21) if x % 2 == 0]

print("Evens:", evens)

pairs = [(x, x**2) for x in range(1, 6)]

print("Pairs:", pairs)

Page 51 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q8.6 [Code Writing] MEDIUM

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 = []

for item in original:

if item not in seen:

[Link](item)

[Link](item)

print("Original:", original)

print("Unique: ", unique)

Q8.7 [Code Writing] MEDIUM

Questi Write a program that takes a 3x3 2D list (matrix) and computes its transpose (swap rows and
on: columns).

Hint: transpose[j][i] = matrix[i][j]. You can use nested list comprehension.

Answe
r:

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

transpose = [[matrix[i][j] for i in range(3)] for j in range(3)]

print("Original:")

for row in matrix: print(row)

print("Transpose:")

for row in transpose: print(row)

Page 52 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q8.8 [Code Writing] MEDIUM

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 = []

for sublist in nested:

for item in sublist:

[Link](item)

return flat

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

print(flatten(nested)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

■ Hard (Advanced) Questions

Q8.9 [Code Writing] HARD

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)

for i in range(n - 1):

for j in range(n - 1 - i):

if arr[j] > arr[j + 1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

print(f"Pass {i+1}: {arr}")

return arr

data = [64, 34, 25, 12, 22, 11, 90]

print("Sorted:", bubble_sort(data))

Page 53 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q8.10 [Code Writing] HARD

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:

import random, string

length = int(input("Password length (min 4): "))

mandatory = [

[Link](string.ascii_uppercase),

[Link](string.ascii_lowercase),

[Link]([Link]),

[Link]([Link])

pool = string.ascii_letters + [Link] + [Link]

rest = [[Link](pool) for _ in range(length - 4)]

pwd = mandatory + rest

[Link](pwd)

print("Password:", "".join(pwd))

Q8.11 [Code Writing] HARD

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:

def binary_search(arr, target):

low, high = 0, len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target: return mid

elif arr[mid] < target: low = mid + 1

else: high = mid - 1

return -1

data = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]

target = int(input("Search for: "))

result = binary_search(data, target)

print(f"Found at index {result}" if result != -1 else "Not found")

Page 54 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q8.12 [Code Writing] HARD

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:

sentence = input("Enter a sentence: ").lower()

words = [Link]()

print("Sorted:", sorted(words))

freq = {}

for w in words:

freq[w] = [Link](w, 0) + 1

print("Frequencies:", freq)

print("Most frequent:", max(freq, key=[Link]))

print("Least frequent:", min(freq, key=[Link]))

Page 55 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 9 Tuples

■ Easy Questions

Q9.1 [Conceptual] EASY

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:

coords = (10, 20, 30, 40, 50)

print(coords[0]) # 10

print(coords[-1]) # 50

print(coords[1:4]) # (20, 30, 40)

Key difference: Tuples are immutable -- you cannot change, add, or remove elements after creation.

Q9.2 [True/False] EASY

Questi True or False: You can have a tuple with only one element by writing t = (5).
on:

Hint: A single-element tuple requires a trailing comma.

Answe
r:
FALSE. (5) is just an integer in parentheses. A single-element tuple MUST include a trailing comma.

t = (5,) # correct tuple

t2 = (5) # just an integer

print(type(t)) # <class 'tuple'>

print(type(t2)) # <class 'int'>

Page 56 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q9.3 [Code Writing] EASY

Questi Write a program that stores two points as tuples, calculates the distance between them, and
on: identifies which quadrant each point lies in.

Hint: d = sqrt((x2-x1)^2 + (y2-y1)^2). Quadrant determined by signs of x and y.

Answe
r:

import math

p1 = (float(input("x1: ")), float(input("y1: ")))

p2 = (float(input("x2: ")), float(input("y2: ")))

d = [Link]((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)

print(f"Distance: {d:.4f}")

def quadrant(p):

x, y = p

if x>0 and y>0: return "Q1"

elif x<0 and y>0: return "Q2"

elif x<0 and y<0: return "Q3"

elif x>0 and y<0: return "Q4"

else: return "On Axis"

print(f"P1 in {quadrant(p1)}, P2 in {quadrant(p2)}")

Q9.4 [Code Tracing] EASY

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

Page 57 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q9.5 [Code Writing] MEDIUM

Questi Demonstrate tuple packing and unpacking. Pack three student attributes (name, marks, grade)
on: into a tuple, then unpack them into separate variables.

Hint: Packing: t = a, b, c Unpacking: a, b, c = t

Answe
r:

# Packing

student = "Ali", 88, "B"

print(f"Packed: {student}")

# Unpacking

name, marks, grade = student

print(f"Name: {name}, Marks: {marks}, Grade: {grade}")

# Extended unpacking

first, *middle, last = (1, 2, 3, 4, 5)

print(f"First: {first}, Middle: {middle}, Last: {last}")

Q9.6 [Code Writing] MEDIUM

Questi Convert a list of student records (each a tuple of name and score) into a sorted leaderboard by
on: score in descending order.

Hint: Use sorted() with key=lambda x: x[1] and reverse=True.

Answe
r:

students = [("Ali",78),("Sara",92),("Umar",85),("Hina",92),("Bilal",67)]

leaderboard = sorted(students, key=lambda x: x[1], reverse=True)

print("=== Leaderboard ===")

for rank, (name, score) in enumerate(leaderboard, start=1):

print(f"{rank}. {name:10} {score}")

Q9.7 [Analytical] MEDIUM

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.

Page 58 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q9.8 [Code Writing] MEDIUM

Questi Write a function that accepts any number of tuples (each representing (value, weight)) and
on: computes the weighted average.

Hint: weighted_avg = sum(value*weight) / sum(weight) Use *args to accept multiple tuples.

Answe
r:

def weighted_average(*data_points):

total_weighted = sum(val * wt for val, wt in data_points)

total_weight = sum(wt for val, wt in data_points)

return total_weighted / total_weight

result = weighted_average((80,3),(90,4),(70,2),(85,3))

print(f"Weighted Average: {result:.2f}")

■ Hard (Advanced) Questions

Q9.9 [Code Writing] HARD

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:

from collections import namedtuple

Student = namedtuple('Student', ['name', 'roll', 'gpa'])

students = [

Student("Ali", "CS-01", 3.8),

Student("Sara", "CS-02", 3.95),

Student("Umar", "CS-03", 3.6),

best = max(students, key=lambda s: [Link])

print(f"Top: {[Link]} | Roll: {[Link]} | GPA: {[Link]}")

Page 59 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q9.10 [Code Writing] HARD

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 = {

("Lahore", "Karachi"): 1210,

("Lahore", "Islamabad"): 375,

("Karachi", "Islamabad"): 1411,

("Lahore", "Peshawar"): 440,

c1 = input("City 1: ").strip().title()

c2 = input("City 2: ").strip().title()

key, alt = (c1,c2), (c2,c1)

if key in distances: print(f"Distance: {distances[key]} km")

elif alt in distances: print(f"Distance: {distances[alt]} km")

else: print("Not in database.")

Q9.11 [Code Writing] HARD

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))

dist = lambda p: [Link](p[0]**2 + p[1]**2)

sorted_pts = sorted(unique, key=dist)

print("Point Distance")

for p in sorted_pts:

print(f" {p} {dist(p):.4f}")

Page 60 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q9.12 [Analytical + Code] HARD

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:

t = (1, 2); l = [1, 2]

print(hash(t)) # works

try:

print(hash(l)) # TypeError

except TypeError as e:

print(f"List not hashable: {e}")

coords = [(1,2),(3,4),(1,2),(5,6),(3,4),(1,2)]

freq = {}

for point in coords:

freq[point] = [Link](point, 0) + 1

for point, count in [Link]():

print(f" {point}: {count} time(s)")

Page 61 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Topic 10 Recursion

■ Easy Questions

Q10.1 [Conceptual] EASY

Questi What is recursion? What are the two essential components of every recursive function? Give a
on: real-world analogy.

Hint: Think of Russian nesting dolls (Matryoshka).

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).

Q10.2 [Code Writing] EASY

Questi Write a recursive function factorial(n) that computes n!. Show the call stack for factorial(4).
on:

Hint: Base case: factorial(0) = 1 Recursive case: factorial(n) = n * factorial(n-1)

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

Page 62 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q10.3 [Code Writing] EASY

Questi Write a recursive function sum_to_n(n) that returns the sum of all integers from 1 to n.
on:

Hint: Base case: sum_to_n(1) = 1 Recursive case: sum_to_n(n) = n + sum_to_n(n-1)

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

Q10.4 [Code Tracing] EASY

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

Page 63 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q10.5 [Code Writing] MEDIUM

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:

# Recursive -- O(2^n) -- slow for large n

def fib_recursive(n):

if n <= 1: return n

return fib_recursive(n-1) + fib_recursive(n-2)

# Iterative -- O(n) -- much faster

def fib_iterative(n):

a, b = 0, 1

for _ in range(n):

a, b = b, a + b

return a

for i in range(10): print(fib_recursive(i), end=" ")

print()

for i in range(10): print(fib_iterative(i), end=" ")

Q10.6 [Code Writing] MEDIUM

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:

def power(base, exp):

if exp == 0:

return 1

return base * power(base, exp - 1)

print(power(2, 10)) # 1024

print(power(3, 5)) # 243

print(power(5, 0)) # 1

Page 64 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q10.7 [Code Writing] MEDIUM

Questi Write a recursive function is_palindrome(s) that checks if a string is a palindrome.


on:

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

Q10.8 [Code Writing] MEDIUM

Questi Implement recursive P(n,r) and C(n,r) using a recursive factorial helper function.
on:

Hint: P(n,r) = n!/(n-r)! C(n,r) = n!/(r!*(n-r)!) Define factorial(n) recursively first.

Answe
r:

def factorial(n):

if n == 0: return 1

return n * factorial(n - 1)

def permutation(n, r):

return factorial(n) // factorial(n - r)

def combination(n, r):

return factorial(n) // (factorial(r) * factorial(n - r))

n, r = 7, 3

print(f"P({n},{r}) = {permutation(n,r)}") # 210

print(f"C({n},{r}) = {combination(n,r)}") # 35

Page 65 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

■ Hard (Advanced) Questions

Q10.9 [Code Writing] HARD

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:

def gcd(a, b):

if b == 0:

return a

return gcd(b, a % b)

def lcm(a, b):

return (a * b) // gcd(a, b)

print(gcd(48, 18)) # 6

print(lcm(12, 18)) # 36

Q10.10 [Code Writing] HARD

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:

def permutations(s, prefix=""):

if len(s) == 0:

print(prefix)

return

for i in range(len(s)):

remaining = s[:i] + s[i+1:]

permutations(remaining, prefix + s[i])

permutations("ABC")

# ABC, ACB, BAC, BCA, CAB, CBA

Page 66 | 10 Topics · 120 Questions · Easy / Medium / Hard


Python Programming — Question Bank CS Lab Series

Q10.11 [Code Writing] HARD

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:

def hanoi(n, source, destination, auxiliary):

if n == 0:

return

hanoi(n-1, source, auxiliary, destination)

print(f"Move disk {n}: {source} -> {destination}")

hanoi(n-1, auxiliary, destination, source)

n = int(input("Number of disks: "))

hanoi(n, "A", "C", "B")

# For n=3: requires 2^3 - 1 = 7 moves

Q10.12 [Code Writing] HARD

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 = []

for item in nested:

if isinstance(item, list):

[Link](flatten_recursive(item))

else:

[Link](item)

return result

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

print(flatten_recursive(deep))

# [1, 2, 3, 4, 5, 6, 7, 8]

Page 67 | 10 Topics · 120 Questions · Easy / Medium / Hard

You might also like