Python technical interviews evaluate a candidate’s grasp of both fundamental language features and deep runtime execution mechanics. Key topics frequently tested include built-in data structure behaviors, object-oriented principles, functional constructs like decorators and generators, and core memory management concepts such as reference counting and garbage collection. Additionally, employers test understanding of Python’s execution environment, including the Global Interpreter Lock (GIL) and dynamic scoping rules. Mastering these concepts through multiple-choice practice helps developers identify hidden edge cases, write idiomatic Python code, and perform confidently in software engineering assessments.
Python Interview Questions MCQs
1 min read
Correct Answer: b) __cause__ is set during explicit chaining with 'from'; __context__ is set during implicit chaining
Explanation:
When using explicit chaining ('raise new from orig'), __cause__ is populated. When an exception occurs inside an except handler without 'from', Python automatically sets __context__.
Correct Answer: b) GeneratorExit
Explanation:
GeneratorExit, KeyboardInterrupt, and SystemExit inherit directly from BaseException to prevent being accidentally caught by 'except Exception:'.
Correct Answer: b) It matches and splits specified exception types, leaving unhandled ones in a new subgroup to propagate
Explanation:
The 'except*' syntax splits matching exceptions from an ExceptionGroup so they can be handled, while remaining unhandled exceptions are re-raised as a subgroup.
Correct Answer: a) It sets __cause__ to None and __suppress_context__ to True, suppressing the display of the original exception context
Explanation:
'from None' explicitly disables exception chaining output by suppressing the display of the underlying exception context.
Correct Answer: b) A truthy value (such as True)
Explanation:
If __exit__() returns a truthy value (e.g., True), Python suppresses the exception that occurred inside the 'with' statement block.
Correct Answer: b) RuntimeError
Explanation:
If a generator catches GeneratorExit and subsequently attempts to yield another value, a RuntimeError is raised.
Correct Answer: a) StopIteration raised inside a generator is transformed into a RuntimeError to prevent accidental iteration termination
Explanation:
PEP 479 changes behavior so that an unhandled StopIteration raised inside a generator is turned into a RuntimeError.
Correct Answer: b) RecursionError
Explanation:
RecursionError (which inherits from RuntimeError) is raised when the interpreter detects maximum call stack depth exhaustion.
Correct Answer: b) LookupError
Explanation:
LookupError is the base class for exceptions raised when a key or index used on a mapping or sequence is invalid.
Correct Answer: b) AttributeError
Explanation:
Attempting to invoke mutating methods like add() or remove() on a frozenset causes AttributeError because those methods are not defined on it.
Correct Answer: b) threading.excepthook is called, and the worker thread terminates while the main process continues
Explanation:
In Python 3.8+, unhandled exceptions in worker threads invoke threading.excepthook, isolating the thread without crashing the main process unless configured otherwise.
Correct Answer: b) contextlib
Explanation:
contextlib.suppress(*exceptions) is a context manager designed to suppress designated exceptions inside its body.
Correct Answer: b) json.decoder.JSONDecodeError
Explanation:
json.loads() raises JSONDecodeError, which is a subclass of ValueError.
Correct Answer: b) The finally return value overrides the try return value
Explanation:
If a finally block executes a return statement, its return value overrides any previous return statement executed in try or except blocks.
Correct Answer: c) It is NOT caught by the adjacent except blocks and propagates outward
Explanation:
Except blocks in a try statement only guard the try block itself; errors occurring inside the else block propagate out.
Correct Answer: b) ValueError
Explanation:
String formatting functions raise ValueError when provided with invalid or inappropriate formatting specifiers.
Correct Answer: b) Exception
Explanation:
User-defined exceptions should inherit from Exception to allow standard 'except Exception:' clauses to handle them while preserving SystemExit and KeyboardInterrupt functionality.
Correct Answer: b) TypeError
Explanation:
Bitwise operators in Python require integer arguments; supplying floats raises 'TypeError: unsupported operand type(s) for &'.
Correct Answer: b) NotImplementedError
Explanation:
NotImplementedError (a subclass of RuntimeError) is raised when derived classes fail to override mandatory abstract methods.
Correct Answer: b) NotImplemented is a special constant returned by binary special methods; NotImplementedError is an Exception class
Explanation:
NotImplemented is a singleton object returned by dunder comparison/arithmetic operators to delegate fallback handling; NotImplementedError is an actual exception class.
Correct Answer: b) SyntaxError
Explanation:
If the module file is located successfully but contains invalid Python syntax, the parsing phase raises a SyntaxError.
Correct Answer: b) e.args
Explanation:
The positional arguments passed to an exception constructor are stored in a tuple assigned to the 'args' attribute.
Correct Answer: b) sys.exc_info()
Explanation:
sys.exc_info() returns details of the exception currently being handled in the active thread context.
Correct Answer: b) TypeError
Explanation:
Tuples are immutable; attempting item assignment raises 'TypeError: 'tuple' object does not support item assignment'.
Correct Answer: b) It raises a RuntimeError stating no active exception to re-raise
Explanation:
A bare 'raise' requires an active exception context in the current thread frame; otherwise, a RuntimeError is raised.
Correct Answer: b) ArithmeticError
Explanation:
ArithmeticError is the built-in base class for math-related numeric exceptions.
Correct Answer: b) StopIteration
Explanation:
Built-in next() function raises StopIteration to signal the completion of iteration.
Correct Answer: b) NameError
Explanation:
eval() evaluates string code dynamically; unquoted identifier names not found in scope raise a NameError.
Correct Answer: b) ValueError
Explanation:
ValueError is raised when an operation or function receives an argument that has the right type but an inappropriate value.
Correct Answer: a) TypeError
Explanation:
TypeError is raised when an operation is performed on an object of unsuitable type.
Correct Answer: a) UnicodeDecodeError
Explanation:
UnicodeDecodeError is raised when byte sequence decoding fails for a given codec.
Correct Answer: a) UnicodeDecodeError -> UnicodeError -> ValueError -> Exception
Explanation:
UnicodeDecodeError subclasses UnicodeError, which subclasses ValueError.
Correct Answer: b) IndexError
Explanation:
list.pop() on an empty list raises 'IndexError: pop from empty list'.
Correct Answer: b) KeyError
Explanation:
set.remove() raises KeyError if the target element is missing. (set.discard() can be used to avoid exceptions).
Correct Answer: b) discard()
Explanation:
set.discard(elem) removes the element if present, and does nothing without error if absent.
Correct Answer: b) ReferenceError
Explanation:
Accessing a weakref proxy whose object has been collected raises ReferenceError.
Correct Answer: a) sys.excepthook
Explanation:
sys.excepthook(type, value, traceback) is called when an uncaught exception occurs.
Correct Answer: b) AssertionError
Explanation:
An assert statement raises AssertionError if the tested condition evaluates to False.
Correct Answer: a) EOFError
Explanation:
input() raises EOFError when reading EOF from stdin.
Correct Answer: b) OSError
Explanation:
In Python 3, IOError and EnvironmentError are aliases/subclasses consolidated under OSError.
Correct Answer: b) FileNotFoundError
Explanation:
FileNotFoundError (a subclass of OSError) is raised when a requested file or path does not exist.
Correct Answer: b) PermissionError
Explanation:
PermissionError (a subclass of OSError) is raised when permission is denied during file operations.
Correct Answer: b) FileExistsError
Explanation:
FileExistsError is raised when attempting to create a file or directory that already exists.
Correct Answer: b) ValueError
Explanation:
Calling I/O methods on closed file objects raises 'ValueError: I/O operation on closed file'.
Correct Answer: b) ValueError
Explanation:
int() cannot directly parse decimal point characters in a string literal without float conversion first, raising a ValueError.
Correct Answer: b) ValueError
Explanation:
Mismatch between target variable count and sequence length produces 'ValueError: not enough values to unpack'.
Correct Answer: b) TypeError
Explanation:
Executing non-callable instances raises 'TypeError: 'int' object is not callable'.
Correct Answer: b) TypeError
Explanation:
Elements added to a set must be hashable; passing a list raises 'TypeError: unhashable type: 'list''.
Correct Answer: b) TypeError
Explanation:
Dictionary keys must be hashable; mutable containers raise 'TypeError: unhashable type'.
Correct Answer: b) TypeError
Explanation:
Direct concatenation of str and int raises 'TypeError: can only concatenate str (not "int") to str'.
Correct Answer: a) It catches all exceptions, including SystemExit and KeyboardInterrupt, making script cancellation difficult
Explanation:
Bare 'except:' traps BaseException derivatives, including system signals, which can inadvertently catch interrupt signals.
Correct Answer: a) Remaining tasks are cancelled and an ExceptionGroup containing failures is raised
Explanation:
asyncio.TaskGroup cancels remaining active tasks upon task failure and propagates aggregated errors via an ExceptionGroup.
Correct Answer: b) BaseException
Explanation:
In Python 3.8+, CancelledError inherits from BaseException so generic 'except Exception:' blocks do not inadvertently intercept task cancellation.
Correct Answer: b) ValueError
Explanation:
math.sqrt(-1) raises 'ValueError: math domain error' because real domain math functions do not support complex output.
Correct Answer: b) Returns complex number 1j without raising an exception
Explanation:
The cmath module handles complex domain computations, returning 1j without raising domain errors.
Correct Answer: b) MemoryError
Explanation:
MemoryError is raised when an operation runs out of available memory.
Correct Answer: b) OverflowError
Explanation:
OverflowError is raised when arithmetic calculation results exceed representable limits.
Correct Answer: b) traceback
Explanation:
traceback.format_exc() returns the formatted stack trace string of the active exception.
Correct Answer: b) ValueError
Explanation:
list.index(x) raises 'ValueError: x is not in list' if the element is not found.
Correct Answer: b) KeyError
Explanation:
dict.pop(key) raises KeyError if key is missing and no default return value is specified.
Correct Answer: b) Returns None without raising an exception
Explanation:
Providing a default argument to dict.pop() prevents KeyError and returns the default.
Correct Answer: b) FutureWarning
Explanation:
FutureWarning targets end-users about upcoming behavioral changes in packages.
Correct Answer: a) DeprecationWarning
Explanation:
DeprecationWarning is directed at developers to signal deprecated code usage.
Correct Answer: a) python -W error script.py
Explanation:
Passing '-W error' instructs the Python warnings filter to elevate warnings to exceptions.
Correct Answer: a) warnings.catch_warnings()
Explanation:
warnings.catch_warnings() copies and restores warning filters upon exiting the context.
Correct Answer: a) Logs an ERROR message and automatically appends exception traceback info
Explanation:
logging.exception() logs at ERROR level and extracts the current exception stack trace from sys.exc_info().
Correct Answer: b) TypeError
Explanation:
Sets are unindexed collections; subscript slicing raises 'TypeError: 'set' object is not subscriptable'.
Correct Answer: b) ValueError
Explanation:
Factorials are only defined for non-negative integers; negative numbers produce ValueError.
Correct Answer: a) ValueError
Explanation:
math.factorial requires integral values and raises ValueError when given floats with non-zero fractional parts.
Correct Answer: b) IndexError
Explanation:
Popping from an empty deque raises 'IndexError: pop from an empty deque'.
Correct Answer: b) queue.Empty
Explanation:
queue.Queue.get_nowait() raises queue.Empty exception when no elements are available.
Correct Answer: b) queue.Full
Explanation:
queue.Queue.put_nowait() raises queue.Full exception when max size is reached.
Correct Answer: b) LookupError
Explanation:
Passing an invalid encoding name to encode() raises 'LookupError: unknown encoding'.
Correct Answer: b) OverflowError
Explanation:
int.to_bytes() raises OverflowError if integer magnitude exceeds specified output length.
Correct Answer: b) TypeError
Explanation:
Sequence repetition requires integer multipliers; floats raise 'TypeError: can't multiply sequence by non-int of type 'float''.
Correct Answer: b) IndexError
Explanation:
Missing positional format arguments raise 'IndexError: Replacement index out of range'.
Correct Answer: a) KeyError
Explanation:
Missing keyword format arguments raise KeyError for the missing placeholder key.
Correct Answer: b) TypeError
Explanation:
Incompatible metaclass inheritance hierarchies trigger 'TypeError: metaclass conflict'.
Correct Answer: a) ProcessLookupError
Explanation:
ProcessLookupError (a subclass of OSError) is raised when target PID is not found.
Correct Answer: b) io.UnsupportedOperation
Explanation:
io.UnsupportedOperation (inheriting from ValueError and OSError) is raised when performing unsupported stream operations.
Correct Answer: b) SystemExit
Explanation:
sys.exit() raises SystemExit exception, which can be caught if clean termination handling is needed.
Correct Answer: a) e.code == 42
Explanation:
SystemExit objects store the exit status code integer in their 'code' attribute.
Correct Answer: b) It is written to sys.unraisablehook / stderr and ignored
Explanation:
Exceptions occurring during object destruction/garbage collection cannot propagate normally and are handled via unraisablehook.
Correct Answer: a) struct.error
Explanation:
The standard struct module raises struct.error on packing or unpacking failures.
Correct Answer: a) pickle.UnpicklingError
Explanation:
The pickle module raises pickle.UnpicklingError when unpickling invalid data streams.
Correct Answer: b) ValueError
Explanation:
open() raises 'ValueError: invalid mode' for unknown mode flag characters.
Correct Answer: a) socket.timeout
Explanation:
socket.timeout (an alias for TimeoutError) is raised when socket read/write calls time out.
Correct Answer: a) ConnectionRefusedError
Explanation:
ConnectionRefusedError is raised when the target socket connection is rejected.
Correct Answer: b) BrokenPipeError
Explanation:
BrokenPipeError is raised when attempting to write to a pipe/socket with no active reader.
Correct Answer: b) SyntaxError
Explanation:
ast.parse raises SyntaxError when parsing invalid Python code.
Correct Answer: b) e.offset
Explanation:
SyntaxError instances store the 1-based character offset index in the 'offset' attribute.
Correct Answer: b) ValueError
Explanation:
compile() raises ValueError if embedded null bytes exist in the source string.
Correct Answer: a) sys.unraisablehook
Explanation:
sys.unraisablehook allows customizing output when exceptions occur in contexts where they cannot be raised (e.g. __del__).
Correct Answer: b) A list of strings representing stack trace lines
Explanation:
traceback.format_exception returns a list of formatted line strings.
Correct Answer: b) TypeError
Explanation:
Unpacking a non-iterable object raises 'TypeError: cannot unpack non-iterable int object'.
Correct Answer: a) AttributeError
Explanation:
Tuples do not possess an append method, raising AttributeError.
Correct Answer: b) ValueError
Explanation:
Hex decoding requires complete byte pairs; odd-length strings raise ValueError.
Correct Answer: b) ValueError
Explanation:
Signal handlers can only be set from the main thread; calling signal.signal() from subthreads raises ValueError.
Correct Answer: b) The exception propagates immediately out of the function call
Explanation:
Exceptions occurring during lazy generator evaluation inside built-ins propagate immediately.
Correct Answer: b) AttributeError
Explanation:
Deleting non-existent object attributes raises AttributeError.
Correct Answer: b) OSError
Explanation:
os.rmdir on non-empty directories raises OSError (specifically ENOTEMPTY).
Correct Answer: b) SyntaxError
Explanation:
exec() parses code strings dynamically and raises SyntaxError if syntax rules are violated.
Correct Answer: b) TypeError
Explanation:
range objects are immutable; item assignment raises 'TypeError: 'range' object does not support item assignment'.
Correct Answer: b) Ensuring system state remains consistent and resources are properly cleaned up even when exceptions occur
Explanation:
Exception safety ensures state consistency and resource release (e.g., using context managers or finally blocks) during error flows.
Related Posts

Java Interfaces and Abstract Classes MCQs
Java interfaces and abstract classes are core constructs used to implement abstraction and enforce design contracts in object-oriented architecture. An…
October 19, 2026By MCQs Generator

Python Modules & Packages MCQs
Python modules are single files containing Python code (functions, classes, and variables) that can be imported and reused across different…
October 19, 2026By MCQs Generator

Python Exception / Error Handling MCQs
Exception handling in Python provides a structured mechanism to catch, handle, and manage runtime errors without abruptly crashing an application.…
October 19, 2026By MCQs Generator
Related Categories

AI & Data Science MCQ
5 topics
By MCQs Generator

Arts & Humanities MCQ
4 topics
By MCQs Generator

Civil Engineering MCQ
4 topics
By MCQs Generator

Commerce & Business MCQ
4 topics
By MCQs Generator

Competitive Exams MCQ
5 topics
By MCQs Generator

Electrical & Electronics Engineering MCQ
3 topics
By MCQs Generator

General Knowledge MCQ
2 topics
By MCQs Generator

General Science MCQ
4 topics
By MCQs Generator

Law & Judiciary MCQ
3 topics
By MCQs Generator

Mechanical Engineering MCQ
4 topics
By MCQs Generator

Medical & Health Sciences MCQ
4 topics
By MCQs Generator

Modern Tech Fields MCQ
3 topics
By MCQs Generator