Python Control Flow MCQs

1 min read

Control flow statements regulate the order in which individual code statements are evaluated and executed in a Python program. Python provides three main control flow mechanisms: sequential execution, selection statements (if, elif, else, and match case), and iteration loops (for and while). Unlike C style languages that utilize curly braces, Python relies strictly on block indentation to define conditional and loop scopes. Modern Python features like loop else clauses, ternary expressions, and structural pattern matching enhance code expressiveness and maintainability. Mastering control flow is fundamental for writing dynamic, bug-free applications and clearing technical assessments.

1. Which of the following keywords is used to begin an alternate condition branch in Python when the initial 'if' statement evaluates to False?

a) else if
b) elseif
c) elif
d) then
Correct Answer: c) elif
Explanation:
Python uses the keyword 'elif' (short for else if) to chain multiple conditional statements together after an initial 'if'.

2. What is the output of the following code snippet? x = 5; print('A') if x > 10 else print('B')

a) A
b) B
c) None
d) SyntaxError
Correct Answer: b) B
Explanation:
This is Python's ternary conditional expression. Since x > 10 evaluates to False, the expression returns and executes the right-hand branch, printing 'B'.

3. What happens when a 'for' loop finishes iterating normally over a sequence without encountering a 'break' statement, and an 'else' block is attached to the loop?

a) The 'else' block is completely ignored.
b) The 'else' block executes.
c) Python raises a RuntimeError.
d) The loop restarts from the beginning.
Correct Answer: b) The 'else' block executes.
Explanation:
In Python, a loop's optional 'else' block executes if and only if the loop terminates normally (without hitting a break statement).

4. What will be printed by this code? for i in range(3): pass; print(i)

a) 0 1 2
b) 2
c) 3
d) NameError
Correct Answer: b) 2
Explanation:
The loop completes and 'i' remains bound to its last iterated value in the current scope, which is 2.

5. What is the result of executing range(5, 1, -1) as a list?

a) [5, 4, 3, 2, 1]
b) [5, 4, 3, 2]
c) [4, 3, 2, 1]
d) []
Correct Answer: b) [5, 4, 3, 2]
Explanation:
The range function excludes the stop boundary (1). With a step of -1, it produces sequence elements starting at 5 down to 2.

6. Which statement immediately terminates the execution of the innermost enclosing loop?

a) continue
b) pass
c) break
d) return
Correct Answer: c) break
Explanation:
The 'break' statement terminates the active loop prematurely and transfers execution to the statement immediately following the loop.

7. What is the primary purpose of the 'continue' statement in a Python loop?

a) To exit the loop entirely.
b) To skip the remaining code in the current iteration and move to the next iteration.
c) To pause execution for a given duration.
d) To restart the entire loop from index zero.
Correct Answer: b) To skip the remaining code in the current iteration and move to the next iteration.
Explanation:
The 'continue' statement skips all remaining statements in the loop's body for the current iteration and advances control back to the loop header.

8. What does the 'pass' statement do in Python control flow?

a) It breaks out of the loop.
b) It raises an exception.
c) It acts as a null operation placeholder where statement syntax is required.
d) It skips the next statement.
Correct Answer: c) It acts as a null operation placeholder where statement syntax is required.
Explanation:
'pass' is a syntactic placeholder that does nothing when executed, allowing empty blocks in structures like if statements, loops, or functions.

9. Introduced in Python 3.10, which keyword pair provides structural pattern matching functionality similar to switch-case?

a) switch / case
b) select / case
c) match / case
d) choose / when
Correct Answer: c) match / case
Explanation:
Python 3.10 introduced structural pattern matching using the 'match' and 'case' soft keywords.

10. In a Python 3.10+ match-case construct, what character acts as the wildcard pattern matching any value (like a default case)?

a) *
b) _
c) default
d) else
Correct Answer: b) _
Explanation:
The single underscore '_' is the wildcard pattern in structural pattern matching that matches any object if no preceding pattern matched.

11. What is the output of the following code? x = 0; while x < 3: x += 1; print(x, end=' ')

a) 0 1 2
b) 1 2 3
c) 0 1 2 3
d) 1 2
Correct Answer: b) 1 2 3
Explanation:
In each iteration, x is incremented before printing. The iterations increment x to 1, then 2, then 3, printing '1 2 3 '.

12. What will be the output of this code snippet? x = 0; while x < 3: print(x, end=' '); x += 1; else: print('End')

a) 0 1 2 End
b) 0 1 2 3 End
c) 0 1 2
d) End
Correct Answer: a) 0 1 2 End
Explanation:
The while loop prints 0, 1, and 2. When x reaches 3, x < 3 becomes False, causing the loop to finish normally and triggering the 'else' block.

13. What happens if a 'break' statement is executed inside a while loop with an 'else' block attached?

a) The 'else' block executes immediately after break.
b) The 'else' block is skipped entirely.
c) An UnboundLocalError is raised.
d) The loop restarts.
Correct Answer: b) The 'else' block is skipped entirely.
Explanation:
When a loop terminates via a 'break' statement, the loop's 'else' clause is bypassed.

14. What is the output of bool([]) in an if condition check?

a) True
b) False
c) None
d) TypeError
Correct Answer: b) False
Explanation:
An empty sequence (like an empty list []) evaluates to False in a boolean context, so the condition fails.

15. Which of the following values evaluates to True inside an 'if' statement condition?

a) 0
b) ''
c) [-1]
d) None
Correct Answer: c) [-1]
Explanation:
Any non-empty collection in Python (even one containing negative numbers or falsy items) evaluates to True.

16. What is the output of the code? count = 0; while count < 2: count += 1; break; else: print('Done'); print('Out')

a) Done Out
b) Out
c) 0 Out
d) Done
Correct Answer: b) Out
Explanation:
The loop executes 'count += 1' and immediately hits 'break'. The 'else' block is skipped, and execution proceeds directly to 'print("Out")'.

17. What is the default start, stop, and step step behavior when range(10) is invoked?

a) start=1, stop=10, step=1
b) start=0, stop=10, step=1
c) start=0, stop=9, step=1
d) start=1, stop=9, step=1
Correct Answer: b) start=0, stop=10, step=1
Explanation:
Single-argument range(stop) defaults start to 0 and step to 1, generating numbers from 0 up to (but not including) stop.

18. What is the output of list(range(0, -5, -1))?

a) [0, -1, -2, -3, -4, -5]
b) [0, -1, -2, -3, -4]
c) []
d) [-1, -2, -3, -4]
Correct Answer: b) [0, -1, -2, -3, -4]
Explanation:
The range starts at 0 and decrements by -1 until reaching the stop limit -5 (excluded).

19. What is the result of list(range(5, 2))?

a) [5, 4, 3]
b) [5, 4, 3, 2]
c) []
d) ValueError
Correct Answer: c) []
Explanation:
By default, the step is +1. Since start (5) is greater than stop (2) with a positive step, range produces an empty sequence.

20. What is the output of the following code? for x in range(1, 4): print(x * 2, end=' ')

a) 1 2 3
b) 2 4 6
c) 2 4 6 8
d) 1 4 9
Correct Answer: b) 2 4 6
Explanation:
The loop iterates through 1, 2, and 3. Multiplying each by 2 yields 2, 4, and 6.

21. What is the output of this nested control structure? for i in range(2): for j in range(2): if i == j: continue; print(f'{i}{j}', end=' ')

a) 00 11
b) 01 10
c) 00 01 10 11
d) 01 11
Correct Answer: b) 01 10
Explanation:
When i == j (at 0,0 and 1,1), 'continue' skips the print statement. Only pairs where i != j (0,1 and 1,0) are printed.

22. How many times will 'Hello' be printed in the following code? i = 5; while i > 0: print('Hello'); i -= 2

a) 2 times
b) 3 times
c) 5 times
d) Infinite times
Correct Answer: b) 3 times
Explanation:
i takes values 5 (prints 1st), 3 (prints 2nd), and 1 (prints 3rd). When i becomes -1, -1 > 0 is False and the loop terminates.

23. What is the output of: x = 10; y = 20; print('X') if x > 15 else print('Y') if y > 15 else print('Z')?

a) X
b) Y
c) Z
d) SyntaxError
Correct Answer: b) Y
Explanation:
This is a chained ternary expression. x > 15 is False, so it evaluates the second branch 'print("Y") if y > 15 else print("Z")'. Since y > 15 is True, 'Y' is printed.

24. Which special protocol method is invoked by a 'for' loop to obtain an iterator object from a collection?

a) __next__()
b) __iter__()
c) __loop__()
d) __getitem__()
Correct Answer: b) __iter__()
Explanation:
A 'for' loop calls iter() on the target sequence, which invokes the sequence's __iter__() dunder method to obtain an iterator.

25. Which method is called repeatedly on an iterator object by a 'for' loop to fetch successive items?

a) __iter__()
b) __next__()
c) __step__()
d) __getnext__()
Correct Answer: b) __next__()
Explanation:
The loop calls next() on the iterator object, invoking its __next__() method until StopIteration is raised.

26. Which exception is raised to signal that an iterator has no more items during loop iteration?

a) IndexError
b) StopIteration
c) IteratorError
d) EndOfString
Correct Answer: b) StopIteration
Explanation:
When __next__() runs out of elements, it raises StopIteration, which tells the 'for' loop to terminate cleanly.

27. What is the output of the following code? x = [1, 2, 3]; it = iter(x); next(it); print(next(it))

a) 1
b) 2
c) 3
d) StopIteration
Correct Answer: b) 2
Explanation:
The first call to next(it) returns 1. The second call advances the iterator and returns 2.

28. In Python 3.10 match-case, how can multiple literal values be matched in a single case clause?

a) case 1, 2, 3:
b) case 1 | 2 | 3:
c) case 1 or 2 or 3:
d) case (1, 2, 3):
Correct Answer: b) case 1 | 2 | 3:
Explanation:
In structural pattern matching, the bitwise OR pipe operator '|' acts as an OR pattern separator within case expressions.

29. In structural pattern matching, what is an extra conditional filter appended to a case clause called?

a) Case shield
b) Guard condition
c) Match filter
d) Clause check
Correct Answer: b) Guard condition
Explanation:
An 'if' clause appended to a pattern in a case statement (e.g., case x if x > 0:) is called a guard condition.

30. What is the result of running this match-case snippet? val = 10; match val: case x if x < 5: print('Low'); case x if x >= 5: print('High')

a) Low
b) High
c) SyntaxError
d) None
Correct Answer: b) High
Explanation:
The pattern binds val (10) to x. The guard 'if x >= 5' evaluates to True (10 >= 5), so 'High' is printed.

31. Which of the following statements about Python's 'if' statement is true?

a) An 'if' statement must always have an 'else' block.
b) Parentheses around the condition are mandatory.
c) Indentation defines the code block associated with the condition.
d) Braces {} are required to delimit statements.
Correct Answer: c) Indentation defines the code block associated with the condition.
Explanation:
Python relies strictly on consistent indentation levels rather than braces or delimiter keywords to define block structures.

32. What will be printed? a = True; b = False; if a and not b: print('1'); else: print('2')

a) 1
b) 2
c) 1 2
d) SyntaxError
Correct Answer: a) 1
Explanation:
a is True and b is False. 'not b' is True. Thus 'True and True' is True, printing '1'.

33. What happens when an exception is raised inside a 'try' block, but no matching 'except' handler is present?

a) The code safely ignores the exception.
b) The program enters an infinite loop.
c) Control jumps to the 'else' block.
d) The exception propagates up the call stack, potentially crashing the program.
Correct Answer: d) The exception propagates up the call stack, potentially crashing the program.
Explanation:
Unhandled exceptions escalate up caller frames until handled by an enclosing try-except or reaching top-level execution, where Python terminates with a traceback.

34. In try-except-else-finally control flow, when does the 'else' block execute?

a) Whenever an exception occurs.
b) Only when NO exceptions were raised in the try block.
c) Always, regardless of exceptions.
d) Only when finally completes.
Correct Answer: b) Only when NO exceptions were raised in the try block.
Explanation:
The 'else' block in exception handling executes if and only if the 'try' block completed without raising any exception.

35. In try-except-finally control flow, when does the 'finally' block execute?

a) Only if an exception occurred.
b) Only if no exception occurred.
c) Always, whether an exception occurred or not.
d) Only if explicitly called.
Correct Answer: c) Always, whether an exception occurred or not.
Explanation:
The 'finally' clause is guaranteed to execute clean-up code regardless of whether the try block raised an exception, caught an exception, or returned.

36. What is the output of the following try block? try: x = 1 / 0; except ZeroDivisionError: print('Div'); finally: print('Fin')

a) Div
b) Fin
c) Div Fin
d) ZeroDivisionError
Correct Answer: c) Div Fin
Explanation:
ZeroDivisionError triggers the except block (printing 'Div'). After handling, the 'finally' block executes (printing 'Fin').

37. What occurs if a 'return' statement is encountered inside both 'try' and 'finally' blocks?

a) The 'try' block's return value takes precedence.
b) The 'finally' block's return value overwrites the 'try' return value.
c) A SyntaxError is raised.
d) Both values are returned as a tuple.
Correct Answer: b) The 'finally' block's return value overwrites the 'try' return value.
Explanation:
When 'finally' executes a return statement, it discards any pending return value or active exception from the preceding try or except blocks.

38. How many times does the while loop execute? x = 10; while x > 10: print(x); x += 1

a) 10 times
b) Infinite times
c) 0 times
d) 1 time
Correct Answer: c) 0 times
Explanation:
The condition 10 > 10 evaluates to False on the initial check, so the loop body never executes.

39. What is the output of: for x in range(3): if x == 1: continue; print(x, end=' ') else: print('End')?

a) 0 2 End
b) 0 1 2 End
c) 0 2
d) End
Correct Answer: a) 0 2 End
Explanation:
1 is skipped due to 'continue', so 0 and 2 print. Because no 'break' occurred, the 'else' clause executes, printing 'End'.

40. What is the output of: for x in range(3): if x == 1: break; print(x, end=' ') else: print('End')?

a) 0 End
b) 0
c) 0 1 End
d) 0 1 2 End
Correct Answer: b) 0
Explanation:
At x = 0, 0 is printed. At x = 1, 'break' triggers. The loop terminates immediately, and the 'else' block is skipped.

41. What will be printed? x = [1, 2]; y = [1, 2]; print('Equal') if x == y else print('Not Equal')

a) Equal
b) Not Equal
c) True
d) False
Correct Answer: a) Equal
Explanation:
The == operator checks value equality. Since x and y have identical contents, x == y evaluates to True.

42. What will be printed? x = [1, 2]; y = [1, 2]; print('Same') if x is y else print('Different')

a) Same
b) Different
c) True
d) SyntaxError
Correct Answer: b) Different
Explanation:
The 'is' operator tests object identity (memory address). Lists are distinct objects in memory, so x is y is False.

43. What is the result of executing: for i in []: print('Loop') else: print('Empty')?

a) Loop
b) Empty
c) Nothing prints
d) TypeError
Correct Answer: b) Empty
Explanation:
The sequence [] is empty, so the loop body executes 0 times. Since no break occurred, the 'else' clause executes immediately.

44. Which of the following statement forms is invalid syntax for a Python if statement?

a) if x > 0: print(x)
b) if x > 0 { print(x) }
c) if (x > 0): print(x)
d) if x > 0: pass
Correct Answer: b) if x > 0 { print(x) }
Explanation:
Python does not use curly braces {} to define code blocks for control flow; using them results in a SyntaxError.

45. What is the output of the code: x = 0; while x < 5: x += 2; if x == 4: continue; print(x, end=' ')

a) 2 4 6
b) 2 6
c) 2 4
d) 0 2 6
Correct Answer: b) 2 6
Explanation:
1st iter: x becomes 2, printed (2). 2nd iter: x becomes 4, skipped by continue. 3rd iter: x becomes 6, loop ends, printed (6).

46. What does a 'with' statement manage using context management protocol?

a) Global variables
b) Resource setup and clean-up (enter/exit)
c) Loop iterations
d) Thread execution priority
Correct Answer: b) Resource setup and clean-up (enter/exit)
Explanation:
The 'with' statement simplifies resource management by invoking __enter__() and ensuring __exit__() executes upon exit.

47. Which two magic methods must an object implement to be used as a context manager in a 'with' statement?

a) __init__ and __del__
b) __enter__ and __exit__
c) __start__ and __stop__
d) __open__ and __close__
Correct Answer: b) __enter__ and __exit__
Explanation:
Context manager protocol objects require __enter__() (executed before entering the with body) and __exit__() (executed on exit).

48. If an exception occurs inside a 'with' block, what arguments are passed to the context manager's __exit__ method?

a) None, None, None
b) exc_type, exc_val, exc_tb
c) True, False, None
d) exception_message, stack_trace
Correct Answer: b) exc_type, exc_val, exc_tb
Explanation:
When an exception occurs, Python passes the exception type, exception value, and traceback object to __exit__(exc_type, exc_val, exc_tb).

49. How can a custom context manager suppress an exception raised within a 'with' statement block?

a) By returning True from __exit__()
b) By returning False from __exit__()
c) By calling sys.suppress()
d) By raising StopIteration in __exit__()
Correct Answer: a) By returning True from __exit__()
Explanation:
If the __exit__() method returns a truthy value (like True), Python suppresses the exception and continues execution normally after the with block.

50. What is the output of the following code? d = {'a': 1, 'b': 2}; for k in d: print(k, end=' ')

a) a b
b) 1 2
c) ('a', 1) ('b', 2)
d) KeyError
Correct Answer: a) a b
Explanation:
Iterating directly over a dictionary iterates over its keys in insertion order.

51. How do you iterate over both keys and values simultaneously in a Python dictionary for loop?

a) for k, v in dict.elements():
b) for k, v in dict.items():
c) for k, v in dict.pairs():
d) for k, v in dict.all():
Correct Answer: b) for k, v in dict.items():
Explanation:
The dict.items() method returns a view of (key, value) tuples, allowing dual variable unpacking in a loop.

52. What is the output of: for i, v in enumerate(['x', 'y']): print(i, v, end=' ')?

a) x 0 y 1
b) 0 x 1 y
c) 1 x 2 y
d) (0, 'x') (1, 'y')
Correct Answer: b) 0 x 1 y
Explanation:
enumerate() yields pairs of (index, item) starting at index 0 by default.

53. What parameter is used in enumerate(iterable, start=N) to change the initial counting index?

a) index
b) start
c) begin
d) offset
Correct Answer: b) start
Explanation:
The 'start' keyword argument specifies the starting integer offset for enumerate (e.g., enumerate(items, start=1)).

54. What will be printed? for a, b in zip([1, 2], ['x', 'y', 'z']): print(a, b, end=' ')

a) 1 x 2 y
b) 1 x 2 y None z
c) ValueError
d) 1 x 2 y 3 z
Correct Answer: a) 1 x 2 y
Explanation:
By default, zip() stops iterating when the shortest input iterable is exhausted.

55. Introduced in Python 3.10, which zip parameter forces zip to raise a ValueError if iterables are of unequal length?

a) strict=True
b) equal=True
c) check=True
d) exact=True
Correct Answer: a) strict=True
Explanation:
zip(*iterables, strict=True) enforces that all zipped iterables must have identical lengths, raising ValueError otherwise.

56. What is the output of this code? nums = [1, 2, 3, 4]; evens = [x for x in nums if x % 2 == 0]; print(evens)

a) [1, 3]
b) [2, 4]
c) [1, 2, 3, 4]
d) True
Correct Answer: b) [2, 4]
Explanation:
This list comprehension filters elements using the condition x % 2 == 0, keeping only even numbers.

57. What is the evaluated output of: [x if x > 2 else 0 for x in [1, 2, 3, 4]]?

a) [3, 4]
b) [0, 0, 3, 4]
c) [1, 2, 0, 0]
d) SyntaxError
Correct Answer: b) [0, 0, 3, 4]
Explanation:
When using an inline if-else inside list comprehensions (ternary clause), it must precede the 'for' statement.

58. What is the output of: x = 5; print('A') if x < 2 else print('B') if x < 10 else print('C')?

a) A
b) B
c) C
d) None
Correct Answer: b) B
Explanation:
5 < 2 is False, moving to the next expression. 5 < 10 is True, so 'B' is executed and printed.

59. What is the output of the following recursion control flow? def f(n): return 1 if n 5 else print('E') if x == 3 else print('L')?

a) G
b) E
c) L
d) SyntaxError
Correct Answer: b) E
Explanation:
x > 5 is False. Next branch evaluates x == 3 which is True, so 'E' is printed.

60. Which of the following is NOT valid Python control flow syntax?

a) if a := 5 > 2: print(a)
b) while (x := x - 1) > 0: pass
c) do { print(x) } while x < 5
d) for _ in range(5): pass
Correct Answer: c) do { print(x) } while x < 5
Explanation:
Python does not support 'do-while' loops. Attempting to use do-while syntax results in a SyntaxError.

61. How can a developer emulate a do-while loop structure in standard Python?

a) using while True with conditional break at end of block
b) using do: ... while condition
c) using loop: ... until condition
d) using for loop with infinite step
Correct Answer: a) using while True with conditional break at end of block
Explanation:
A 'while True' loop executing logic first and then checking a exit condition with 'if condition: break' reproduces do-while behavior.

62. What will be printed? x = 1; while x 0 else pass?

a) 1 2
b) SyntaxError
c) 0 1 2
d) 1
Correct Answer: b) SyntaxError
Explanation:
In Python conditional ternary expressions (a if condition else b), both branches must be valid expressions. 'pass' is a statement, not an expression, causing a SyntaxError.

63. What is the output of: print([i for i in range(5) if i % 2 != 0])?

a) [0, 2, 4]
b) [1, 3]
c) [1, 2, 3, 4, 5]
d) [0, 1, 3]
Correct Answer: b) [1, 3]
Explanation:
The comprehension checks i % 2 != 0 (odd numbers), yielding [1, 3].

64. How many values will list(range(10, 0, -2)) contain?

a) 5 values
b) 4 values
c) 6 values
d) 10 values
Correct Answer: a) 5 values
Explanation:
The generated numbers are 10, 8, 6, 4, 2 (stopping before 0), containing 5 elements.

65. Which of the following built-in functions takes an iterable of booleans and returns True if ALL elements evaluate to True?

a) any()
b) all()
c) every()
d) check_all()
Correct Answer: b) all()
Explanation:
all(iterable) returns True if every element in the iterable evaluates to True (or if iterable is empty).

66. Which built-in function returns True if AT LEAST ONE element in an iterable evaluates to True?

a) all()
b) any()
c) some()
d) one()
Correct Answer: b) any()
Explanation:
any(iterable) returns True if at least one item in the iterable is truthy.

67. What is the result of all([]) and any([])?

a) True and True
b) True and False
c) False and True
d) False and False
Correct Answer: b) True and False
Explanation:
all([]) returns True by definition (vacuous truth), while any([]) returns False because no truthy element exists.

68. What is the output of: x = 10; assert x == 5, 'Error!'; print('OK')?

a) OK
b) AssertionError: Error!
c) Error!
d) SyntaxError
Correct Answer: b) AssertionError: Error!
Explanation:
The assert statement checks condition x == 5 (False), raising an AssertionError with the message string 'Error!'.

69. How can python assertions be globally disabled in production execution?

a) Running python with -O (optimize) flag.
b) Setting sys.assert = False.
c) Using try-except AssertionBlocks.
d) Importing no_assert module.
Correct Answer: a) Running python with -O (optimize) flag.
Explanation:
Executing Python scripts using the command line flag -O strips assert statements from compiled bytecode.

70. What is the result of: val = 2; match val: case 1: print('A'); case 2: print('B'); case _: print('C')?

a) A
b) B
c) C
d) A B
Correct Answer: b) B
Explanation:
The match expression matches literal 2 and prints 'B'.

71. What is the output of: res = 'Even' if 4 % 2 == 0 else 'Odd'; print(res)?

a) Even
b) Odd
c) True
d) None
Correct Answer: a) Even
Explanation:
4 % 2 == 0 is True, so res receives 'Even'.

72. In structural pattern matching, how do you capture a matched sub-pattern into a variable using an alias?

a) case [1, 2] as pair:
b) case [1, 2] -> pair:
c) case pair = [1, 2]:
d) case [1, 2] (pair):
Correct Answer: a) case [1, 2] as pair:
Explanation:
The 'as' keyword binds matched sub-patterns to a variable alias inside match-case statements.

73. What happens when break statement is invoked outside of a loop in Python script?

a) Program exits immediately with status 0.
b) Python interpreter raises SyntaxError.
c) It acts as a pass statement.
d) Runtime raises BreakException.
Correct Answer: b) Python interpreter raises SyntaxError.
Explanation:
'break' outside a loop causes Python parser to raise 'SyntaxError: 'break' outside loop'.

74. What happens when 'continue' is invoked outside of a loop in Python?

a) Script restarts.
b) Python interpreter raises SyntaxError.
c) Program terminates cleanly.
d) Nothing happens.
Correct Answer: b) Python interpreter raises SyntaxError.
Explanation:
'continue' outside a loop triggers 'SyntaxError: 'continue' not properly in loop'.

75. What is the output of: for x in (1, 2, 3): break; print(x)?

a) 1
b) 3
c) NameError
d) Nothing prints
Correct Answer: a) 1
Explanation:
In the first iteration, x is assigned 1, then 'break' terminates the loop. 'x' retains value 1 and is printed.

76. What will be the output of: x = 0; while x < 3: x += 1; if x == 1: print(x, end=' ') else: break?

a) 1
b) 1 2 3
c) 1 2
d) 0 1
Correct Answer: a) 1
Explanation:
Iter 1: x=1, prints '1 '. Iter 2: x=2, condition x==1 is False, executes 'else: break', terminating loop.

77. What is the result of: print(list(filter(lambda x: x > 2, [1, 2, 3, 4])))?

a) [3, 4]
b) [1, 2]
c) [True, True]
d) [2, 3, 4]
Correct Answer: a) [3, 4]
Explanation:
filter() tests elements against condition x > 2, retaining only 3 and 4.

78. What is the output of: x = 2; y = 3; print('Yes') if x == 2 and y == 4 else print('No')?

a) Yes
b) No
c) True
d) False
Correct Answer: b) No
Explanation:
x == 2 is True, but y == 4 is False. 'True and False' is False, so 'No' is printed.

79. What is the output of: try: raise ValueError('Err'); except Exception as e: print(type(e).__name__)?

a) ValueError
b) Exception
c) Err
d) TypeError
Correct Answer: a) ValueError
Explanation:
type(e).__name__ returns the exact class name of the raised exception instance, which is 'ValueError'.

80. What is the output of: for i in range(1, 4): print(i ** 2, end=' ')?

a) 1 4 9
b) 1 2 3
c) 1 4 9 16
d) 2 4 6
Correct Answer: a) 1 4 9
Explanation:
i takes values 1, 2, 3. i ** 2 computes 1**2=1, 2**2=4, 3**2=9.

81. What is the output of: x = 10; print('A') if x > 20 else print('B') if x > 5 else print('C')?

a) A
b) B
c) C
d) None
Correct Answer: b) B
Explanation:
x > 20 is False. The second branch checks x > 5 (10 > 5), which is True, so 'B' is printed.

82. Which statement correctly describes Python's short-circuit evaluation in control conditions?

a) In 'A and B', if A is False, B is not evaluated.
b) In 'A or B', if A is False, B is not evaluated.
c) Python always evaluates all expressions regardless of logical operators.
d) Short-circuit evaluation occurs only in match-case blocks.
Correct Answer: a) In 'A and B', if A is False, B is not evaluated.
Explanation:
'and' short-circuits as soon as a falsy operand is found; 'or' short-circuits when a truthy operand is found.

83. What will be printed? x = [0]; print('Truthy') if x else print('Falsy')

a) Truthy
b) Falsy
c) 0
d) TypeError
Correct Answer: a) Truthy
Explanation:
[0] is a non-empty list, and non-empty lists are truthy in Python boolean evaluation.

84. What is the output of: x = 5; while x > 0: x -= 1; if x == 2: break; else: print('Finished')?

a) Finished
b) Nothing is printed
c) 2
d) SyntaxError
Correct Answer: b) Nothing is printed
Explanation:
When x decrements to 2, 'break' triggers. The loop exits immediately, bypassing the loop's 'else' block.

85. What is the result of executing: list(range(3, 3))?

a) [3]
b) []
c) [0, 1, 2]
d) ValueError
Correct Answer: b) []
Explanation:
When start equals stop in range(start, stop), the sequence generated is empty [].

86. What is the output of: x = 0; if x := 5 > 2: print(x)?

a) True
b) 5
c) 2
d) SyntaxError
Correct Answer: a) True
Explanation:
The walrus operator := assigns the evaluation of (5 > 2), which is True, to x and returns True to the if condition.

87. Which of the following describes the execution order of context manager methods in a 'with' statement?

a) __enter__ runs before block execution, __exit__ runs after block execution.
b) __exit__ runs before block execution, __enter__ runs after block execution.
c) __enter__ and __exit__ run simultaneously in parallel threads.
d) __enter__ runs only if an error occurs.
Correct Answer: a) __enter__ runs before block execution, __exit__ runs after block execution.
Explanation:
The context manager protocol calls __enter__() prior to executing the code block, and __exit__() when exiting the block.
← Previous: Python Arrays MCQs
Next →: Python Functions MCQs
Newpython variables & datatypes MCQs

Python Variables & Data Types MCQs

Variables in Python act as dynamic references reserved in memory to store objects, operating without explicit data type declarations due…

By MCQs Generator
NewPython Strings MCQs

Python Strings MCQs

In Python, a string (str) is an immutable sequence of Unicode characters used to represent text data. Defined using single,…

By MCQs Generator
NewLatest Python Loops MCQs

Latest Python Loops MCQs

Loops in Python provide the fundamental mechanism for executing a block of code repeatedly until a specified condition is met…

By MCQs Generator