100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

Previous Exam Questions on Python

Previously asked exam-style Python and CS-fundamentals questions with worked answers for revision.

Concurrency & Interview PrepIntermediate18 min readJul 7, 2026
Analogies

1. Overview

This section collects exam-style questions spanning Python syntax, core data structures, recursion, and algorithmic complexity -- the kind commonly asked in written or practical Python exams. Work through each question, attempt the code traces by hand before checking the explanation, and use the Quick Reference for last-minute revision.

🏏

Cricket analogy: Like a written cricket-coaching exam covering rules, field placements, and scoring math, this section mixes syntax questions with hand-traced calculations you check afterward, then a Quick Reference card for last-minute revision before the paper.

2. Frequently Asked Questions

Write a Python function to check if a number is prime. What is its time complexity?

A simple approach checks divisibility from 2 up to the square root of n: def is_prime(n): return n > 1 and all(n % i for i in range(2, int(n**0.5) + 1)). Checking divisors only up to sqrt(n) gives a time complexity of O(sqrt(n)) instead of the naive O(n).

🏏

Cricket analogy: Checking primality only up to sqrt(n) is like a fielding captain only checking for run-out chances up to the halfway mark of the pitch instead of scanning the entire ground -- far fewer checks, same correct result.

What is the difference between compiled and interpreted languages? Where does Python fit?

A compiled language translates source code into machine code ahead of time (e.g., C); an interpreted language executes source code (or an intermediate form) line by line at run time via an interpreter (e.g., classic BASIC). Python is a hybrid: source is first compiled to platform-independent bytecode (.pyc), which the CPython virtual machine then interprets at run time.

🏏

Cricket analogy: Compiled is like a bowling machine pre-programmed with a full sequence of deliveries before the session starts, while interpreted is like a live bowler reacting ball by ball; Python is hybrid -- a coach's pre-set plan (bytecode) that's still executed live.

What is the output of the following code?

python
for i in range(5):
    if i == 3:
        break
else:
    print("Loop completed")
print(i)

A for-loop's else clause runs only if the loop completes without hitting a break. Here, break fires when i == 3, so the else block is skipped. The loop variable i retains its last value, 3, when break executed. So the only output is 3.

🏏

Cricket analogy: A for-loop's else is like a 'target achieved' bonus that only triggers if the chase completes all 50 overs without a batsman being run out early -- since a wicket (break) fell at over 3, the bonus is skipped, and the scoreboard shows 3.

Explain the time complexity of common list operations.

Indexing (lst[i]) is O(1). Appending to the end (lst.append(x)) is O(1) amortized. Inserting at the front or middle (lst.insert(0, x)) is O(n) because subsequent elements must shift. Searching for a value (x in lst) is O(n) since it may scan the whole list.

🏏

Cricket analogy: Indexing the scorecard by over number is instant (O(1)), appending the latest ball to the end is instant, but inserting a forgotten over at the start means renumbering every later over (O(n)), and searching for a specific score means scanning the whole card (O(n)).

What is recursion? Write a recursive factorial function and trace factorial(4).

Recursion is when a function calls itself to solve smaller instances of the same problem, until a base case stops further calls. def factorial(n): return 1 if n <= 1 else n * factorial(n-1). Tracing factorial(4): 4 * factorial(3) = 4 * (3 * factorial(2)) = 4 * (3 * (2 * factorial(1))) = 4 * 3 * 2 * 1 = 24.

🏏

Cricket analogy: Recursion is like calculating a team's total run rate by asking 'what was the rate before this over, plus this over's runs' repeatedly back to over one -- factorial(4) unwinds the same way: 4*(3*(2*(1))) = 24.

Differentiate between a stack and a queue and how each can be implemented in Python.

A stack is LIFO (Last-In-First-Out) -- the most recently added item is removed first; a plain Python list works well via append()/pop(). A queue is FIFO (First-In-First-Out) -- the earliest added item is removed first; collections.deque is preferred over a list because popleft() is O(1), whereas list.pop(0) is O(n).

🏏

Cricket analogy: A stack is like a pile of bats where the last one placed on top is grabbed first (LIFO), while a queue is like the batting order where the first player padded up bats first (FIFO), and deque handles substitutions from the front efficiently.

What is the output of the following code?

python
a = [1, 2, 3]
b = a[:]
b.append(4)
print(a, b)

Slicing with a[:] creates a shallow copy -- a new list object with the same elements. Appending to b does not affect a. Output: [1, 2, 3] [1, 2, 3, 4].

🏏

Cricket analogy: Slicing a scorecard with a[:] is like photocopying the full innings card into a new sheet b -- adding a fifth entry to the photocopy doesn't touch the original, so a stays [1,2,3] and b becomes [1,2,3,4].

What is Big-O notation and why is it used?

Big-O notation describes how an algorithm's running time (or space) grows relative to input size n, in the worst case, ignoring constant factors. It lets you compare algorithms' scalability independent of hardware, e.g., O(n) linear search vs O(log n) binary search.

🏏

Cricket analogy: Big-O is like comparing bowling strategies by how many extra deliveries they need as the target grows, ignoring the exact stadium -- a well-set field (O(log n) binary search style) scales far better than searching every fielder position one by one (O(n)).

What is the difference between a syntax/compile-time error and a runtime exception in Python?

A syntax error is caught by Python's parser before any code runs, e.g., a missing colon after if x: -- the program never starts executing. A runtime exception (e.g., ZeroDivisionError, IndexError) occurs while the program is executing valid syntax, typically due to invalid operations on data encountered during execution.

🏏

Cricket analogy: A syntax error is like the umpire refusing to start the match because the pitch dimensions are wrong -- play never begins; a runtime exception is like a valid match that starts fine but a batsman gets run out mid-innings due to a bad call.

What does the following code output?

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

print(fib(6))

The Fibonacci sequence starting fib(0)=0, fib(1)=1 continues 1, 2, 3, 5, 8 for fib(2) through fib(6). So fib(6) evaluates to 8.

🏏

Cricket analogy: Fibonacci is like a run-rate sequence where each over's target is the sum of the previous two overs' scores -- starting 0, 1, it builds 1, 2, 3, 5, 8, so by the sixth over (fib(6)) the target sits at 8.

3. Quick Reference

  • List indexing is O(1); append is O(1) amortized; insert at front and linear search are O(n).
  • A for-loop's else runs only when the loop finishes without hitting break.
  • Slicing (a[:]) makes a shallow copy, not a reference to the same list.
  • Recursion always needs a base case to terminate; otherwise it causes infinite recursion / RecursionError.
  • Stacks are LIFO (use list.append/pop); queues are FIFO (use collections.deque).

4. Key Takeaways

  • Know the time complexity of common list operations cold -- it's a frequent exam topic.
  • Trace for...else and recursive functions carefully by hand; exams love these code-tracing questions.
  • Slicing produces a shallow copy, distinct from simple assignment which shares the same object.
  • Big-O describes worst-case growth rate, useful for comparing algorithm scalability.
  • Syntax errors are caught before execution; runtime exceptions occur during execution.

Practice what you learned

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#PreviousExamQuestionsOnPython#Previous#Exam#Questions#Frequently#StudyNotes#SkillVeris