Python Interview Questions MCQs

1 min read

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.

1. What is the primary difference between __cause__ and __context__ attributes on Python exception objects?

a) __cause__ is set during implicit chaining; __context__ is set during explicit chaining with 'from'
b) __cause__ is set during explicit chaining with 'from'; __context__ is set during implicit chaining
c) __cause__ holds the traceback object while __context__ holds the exception string
d) They are deprecated synonyms for __traceback__ in Python 3
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__.

2. Which of the following built-in exceptions inherits directly from BaseException rather than Exception?

a) KeyError
b) GeneratorExit
c) MemoryError
d) RecursionError
Correct Answer: b) GeneratorExit
Explanation:
GeneratorExit, KeyboardInterrupt, and SystemExit inherit directly from BaseException to prevent being accidentally caught by 'except Exception:'.

3. In Python 3.11+, how does 'except*' syntax filter an ExceptionGroup?

a) It converts all exceptions inside the group to strings
b) It matches and splits specified exception types, leaving unhandled ones in a new subgroup to propagate
c) It forces synchronous execution of asynchronous tasks
d) It suppresses all non-matching exceptions automatically
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.

4. What happens when 'raise Exception() from None' is executed inside an except block?

a) It sets __cause__ to None and __suppress_context__ to True, suppressing the display of the original exception context
b) It raises a TypeError because None is not an exception instance
c) It clears the current thread execution stack
d) It triggers sys.excepthook immediately
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.

5. What is the return value of a custom context manager's __exit__ method if it wants to swallow an exception raised within the 'with' block?

a) None
b) A truthy value (such as True)
c) False
d) The exception instance itself
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.

6. Which exception is raised when a generator yields a value after its close() method has been called?

a) StopIteration
b) RuntimeError
c) GeneratorExit
d) ValueError
Correct Answer: b) RuntimeError
Explanation:
If a generator catches GeneratorExit and subsequently attempts to yield another value, a RuntimeError is raised.

7. What is the effect of PEP 479 implemented in Python 3.7+ regarding StopIteration inside generators?

a) StopIteration raised inside a generator is transformed into a RuntimeError to prevent accidental iteration termination
b) StopIteration is ignored and converted to None
c) Generators can no longer raise exceptions
d) StopIteration automatically restarts the generator
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.

8. What exception is raised when sys.setrecursionlimit() threshold is exceeded?

a) StackOverflowError
b) RecursionError
c) MemoryError
d) OverflowError
Correct Answer: b) RecursionError
Explanation:
RecursionError (which inherits from RuntimeError) is raised when the interpreter detects maximum call stack depth exhaustion.

9. Which built-in exception class serves as the direct superclass for both KeyError and IndexError?

a) CollectionError
b) LookupError
c) AccessError
d) ContainerError
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.

10. What exception is raised when attempting to mutate a frozenset via non-existent methods or operators?

a) TypeError
b) AttributeError
c) ValueError
d) KeyError
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.

11. What exception is raised if an unhandled error occurs during execution of a thread created by the threading module in Python 3.8+?

a) It crashes the main thread immediately
b) threading.excepthook is called, and the worker thread terminates while the main process continues
c) SystemExit is raised in the main thread
d) ThreadError is raised across all threads
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.

12. Which module in the standard library provides the suppress context manager for ignoring specified exception types?

a) sys
b) contextlib
c) traceback
d) exceptions
Correct Answer: b) contextlib
Explanation:
contextlib.suppress(*exceptions) is a context manager designed to suppress designated exceptions inside its body.

13. What exception type is raised by json.loads() when presented with malformed JSON string input?

a) ValueError
b) json.decoder.JSONDecodeError
c) SyntaxError
d) TypeError
Correct Answer: b) json.decoder.JSONDecodeError
Explanation:
json.loads() raises JSONDecodeError, which is a subclass of ValueError.

14. What happens if a return statement is present in both the try block and the finally block of a function?

a) The try return value is preserved
b) The finally return value overrides the try return value
c) A SyntaxError is raised
d) A tuple of both values is returned
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.

15. What occurs when an exception is raised inside the 'else' block of a try-except-else statement?

a) It is caught by the adjacent except blocks in the same statement
b) It bypasses the finally block
c) It is NOT caught by the adjacent except blocks and propagates outward
d) It is converted to a SystemError
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.

16. Which built-in exception is raised when string formatting fails due to mismatched conversion specifications?

a) FormatError
b) ValueError
c) TypeError
d) StringError
Correct Answer: b) ValueError
Explanation:
String formatting functions raise ValueError when provided with invalid or inappropriate formatting specifiers.

17. What is the default inheritance base for custom user-defined exceptions in Python best practices?

a) BaseException
b) Exception
c) RuntimeError
d) Object
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.

18. What error is raised when performing bitwise operations on floating-point values (e.g. 3.14 & 2.0)?

a) ValueError
b) TypeError
c) BitwiseError
d) ArithmeticError
Correct Answer: b) TypeError
Explanation:
Bitwise operators in Python require integer arguments; supplying floats raises 'TypeError: unsupported operand type(s) for &'.

19. Which exception is raised when an abstract method in an Abstract Base Class (ABC) is invoked without an implementation?

a) AbstractError
b) NotImplementedError
c) AttributeError
d) MethodError
Correct Answer: b) NotImplementedError
Explanation:
NotImplementedError (a subclass of RuntimeError) is raised when derived classes fail to override mandatory abstract methods.

20. What is the fundamental difference between 'NotImplemented' and 'NotImplementedError' in Python?

a) They are identical aliases
b) NotImplemented is a special constant returned by binary special methods; NotImplementedError is an Exception class
c) NotImplemented is an exception; NotImplementedError is a function
d) NotImplemented was removed in Python 3
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.

21. Which exception is raised when an imported module file exists but cannot be parsed due to invalid code syntax?

a) ModuleNotFoundError
b) SyntaxError
c) ImportError
d) LoadError
Correct Answer: b) SyntaxError
Explanation:
If the module file is located successfully but contains invalid Python syntax, the parsing phase raises a SyntaxError.

22. What attribute of an Exception object stores the tuple of arguments provided during its instantiation?

a) e.message
b) e.args
c) e.params
d) e.data
Correct Answer: b) e.args
Explanation:
The positional arguments passed to an exception constructor are stored in a tuple assigned to the 'args' attribute.

23. Which function in the sys module returns a tuple containing (type, value, traceback) for the exception currently being handled?

a) sys.get_exception()
b) sys.exc_info()
c) sys.traceback()
d) sys.last_error()
Correct Answer: b) sys.exc_info()
Explanation:
sys.exc_info() returns details of the exception currently being handled in the active thread context.

24. What error is raised when attempting to modify a tuple using index assignment (e.g., t = (1, 2); t[0] = 9)?

a) ValueError
b) TypeError
c) IndexError
d) AttributeError
Correct Answer: b) TypeError
Explanation:
Tuples are immutable; attempting item assignment raises 'TypeError: 'tuple' object does not support item assignment'.

25. What happens if a bare 'raise' statement is executed inside a finally block when no exception was active in the try/except block?

a) It silently succeeds
b) It raises a RuntimeError stating no active exception to re-raise
c) It exits the interpreter with code 0
d) It raises a NameError
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.

26. Which exception class is the common parent class for ZeroDivisionError, OverflowError, and FloatingPointError?

a) MathError
b) ArithmeticError
c) NumericError
d) CalculationError
Correct Answer: b) ArithmeticError
Explanation:
ArithmeticError is the built-in base class for math-related numeric exceptions.

27. What exception is raised when calling next() on an iterator that has reached exhaustion?

a) IndexError
b) StopIteration
c) KeyError
d) EndIterator
Correct Answer: b) StopIteration
Explanation:
Built-in next() function raises StopIteration to signal the completion of iteration.

28. Which exception is raised when an unquoted string variable name is evaluated via eval() and not found in local/global scope?

a) ValueError
b) NameError
c) SyntaxError
d) TypeError
Correct Answer: b) NameError
Explanation:
eval() evaluates string code dynamically; unquoted identifier names not found in scope raise a NameError.

29. What exception is raised when a function receives an argument with the correct data type but an invalid value?

a) TypeError
b) ValueError
c) AttributeError
d) DomainError
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.

30. What exception is raised when an operation or function is applied to an object of inappropriate type?

a) TypeError
b) ValueError
c) AttributeError
d) ClassError
Correct Answer: a) TypeError
Explanation:
TypeError is raised when an operation is performed on an object of unsuitable type.

31. What exception is raised when an attempt to decode bytes to a string fails using UTF-8 encoding?

a) UnicodeDecodeError
b) UnicodeEncodeError
c) ValueError
d) TypeError
Correct Answer: a) UnicodeDecodeError
Explanation:
UnicodeDecodeError is raised when byte sequence decoding fails for a given codec.

32. What is the inheritance hierarchy for UnicodeDecodeError?

a) UnicodeDecodeError -> UnicodeError -> ValueError -> Exception
b) UnicodeDecodeError -> TypeError -> Exception
c) UnicodeDecodeError -> EncodingError -> BaseException
d) UnicodeDecodeError -> IOError -> OSError
Correct Answer: a) UnicodeDecodeError -> UnicodeError -> ValueError -> Exception
Explanation:
UnicodeDecodeError subclasses UnicodeError, which subclasses ValueError.

33. What error is raised when popping an element from an empty list using list.pop()?

a) KeyError
b) IndexError
c) ValueError
d) EmptyError
Correct Answer: b) IndexError
Explanation:
list.pop() on an empty list raises 'IndexError: pop from empty list'.

34. What exception is raised when set.remove(elem) is called with an element not present in the set?

a) IndexError
b) KeyError
c) ValueError
d) AttributeError
Correct Answer: b) KeyError
Explanation:
set.remove() raises KeyError if the target element is missing. (set.discard() can be used to avoid exceptions).

35. Which set method removes an element without raising an exception if the element is not found?

a) remove()
b) discard()
c) pop()
d) clear()
Correct Answer: b) discard()
Explanation:
set.discard(elem) removes the element if present, and does nothing without error if absent.

36. What exception occurs when accessing a weak reference proxy after its referent object has been garbage collected?

a) AttributeError
b) ReferenceError
c) PointerError
d) NullError
Correct Answer: b) ReferenceError
Explanation:
Accessing a weakref proxy whose object has been collected raises ReferenceError.

37. Which standard library function overrides the default handler for uncaught exceptions in the main thread?

a) sys.excepthook
b) sys.set_error_handler
c) traceback.catch_all
d) builtins.handle_exception
Correct Answer: a) sys.excepthook
Explanation:
sys.excepthook(type, value, traceback) is called when an uncaught exception occurs.

38. What exception is raised by the assert statement when its expression evaluates to False?

a) TypeError
b) AssertionError
c) ValueError
d) RuntimeError
Correct Answer: b) AssertionError
Explanation:
An assert statement raises AssertionError if the tested condition evaluates to False.

39. What exception is raised when input() encounters an End-Of-File (EOF) condition without reading data?

a) EOFError
b) IOError
c) InputError
d) StreamError
Correct Answer: a) EOFError
Explanation:
input() raises EOFError when reading EOF from stdin.

40. Which base class consolidated IOError, EnvironmentError, and WindowsError in Python 3?

a) SystemError
b) OSError
c) FileError
d) RuntimeError
Correct Answer: b) OSError
Explanation:
In Python 3, IOError and EnvironmentError are aliases/subclasses consolidated under OSError.

41. What exception is raised when trying to open a non-existent file in read mode ('r') with open()?

a) FileMissingError
b) FileNotFoundError
c) PathError
d) IOError
Correct Answer: b) FileNotFoundError
Explanation:
FileNotFoundError (a subclass of OSError) is raised when a requested file or path does not exist.

42. What exception is raised when opening a file fails due to insufficient file system permissions?

a) AccessError
b) PermissionError
c) SecurityError
d) OSError
Correct Answer: b) PermissionError
Explanation:
PermissionError (a subclass of OSError) is raised when permission is denied during file operations.

43. What error is raised when creating a directory using os.mkdir() if the directory already exists?

a) DirectoryExistsError
b) FileExistsError
c) PathError
d) OSError
Correct Answer: b) FileExistsError
Explanation:
FileExistsError is raised when attempting to create a file or directory that already exists.

44. Which exception is raised when performing read/write operations on an already closed file handle?

a) ClosedFileError
b) ValueError
c) IOError
d) AttributeError
Correct Answer: b) ValueError
Explanation:
Calling I/O methods on closed file objects raises 'ValueError: I/O operation on closed file'.

45. What exception is raised when converting string '12.34' directly using int('12.34')?

a) TypeError
b) ValueError
c) CastError
d) FloatError
Correct Answer: b) ValueError
Explanation:
int() cannot directly parse decimal point characters in a string literal without float conversion first, raising a ValueError.

46. What error is raised when unpacking a 2-element tuple into 3 target variables (x, y, z = (1, 2))?

a) IndexError
b) ValueError
c) TypeError
d) UnpackError
Correct Answer: b) ValueError
Explanation:
Mismatch between target variable count and sequence length produces 'ValueError: not enough values to unpack'.

47. What exception is raised when attempting to call a non-callable object like an integer (e.g. obj = 5; obj())?

a) AttributeError
b) TypeError
c) ValueError
d) CallError
Correct Answer: b) TypeError
Explanation:
Executing non-callable instances raises 'TypeError: 'int' object is not callable'.

48. What exception is raised when inserting an unhashable object (such as a list) into a set?

a) ValueError
b) TypeError
c) HashError
d) SetError
Correct Answer: b) TypeError
Explanation:
Elements added to a set must be hashable; passing a list raises 'TypeError: unhashable type: 'list''.

49. Which exception is raised when using a unhashable object as a dictionary key?

a) KeyError
b) TypeError
c) ValueError
d) DictError
Correct Answer: b) TypeError
Explanation:
Dictionary keys must be hashable; mutable containers raise 'TypeError: unhashable type'.

50. What exception is raised when attempting to concatenate a string and an integer directly ('age: ' + 20)?

a) ValueError
b) TypeError
c) ConcatError
d) AttributeError
Correct Answer: b) TypeError
Explanation:
Direct concatenation of str and int raises 'TypeError: can only concatenate str (not "int") to str'.

51. Which statement about bare 'except:' clauses is correct?

a) It catches all exceptions, including SystemExit and KeyboardInterrupt, making script cancellation difficult
b) It only catches subclasses of Exception
c) It is required at the end of every try block
d) It raises a SyntaxError in Python 3
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.

52. What happens if an unhandled exception occurs inside a worker thread managed by asyncio.TaskGroup in Python 3.11+?

a) Remaining tasks are cancelled and an ExceptionGroup containing failures is raised
b) The error is silently ignored
c) The event loop terminates instantly without cleanup
d) SystemExit is raised in the main thread
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.

53. In Python 3.8+, what base class does asyncio.CancelledError derive from?

a) Exception
b) BaseException
c) RuntimeError
d) StandardError
Correct Answer: b) BaseException
Explanation:
In Python 3.8+, CancelledError inherits from BaseException so generic 'except Exception:' blocks do not inadvertently intercept task cancellation.

54. What exception is raised when math.sqrt(-1) is executed in the standard math module?

a) ZeroDivisionError
b) ValueError
c) ArithmeticError
d) ComplexError
Correct Answer: b) ValueError
Explanation:
math.sqrt(-1) raises 'ValueError: math domain error' because real domain math functions do not support complex output.

55. What is the result of executing cmath.sqrt(-1) in the cmath module?

a) Raises ValueError
b) Returns complex number 1j without raising an exception
c) Raises TypeError
d) Returns NaN
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.

56. Which built-in exception is raised when allocating memory for a massive array fails?

a) BufferError
b) MemoryError
c) OverflowError
d) AllocationError
Correct Answer: b) MemoryError
Explanation:
MemoryError is raised when an operation runs out of available memory.

57. Which built-in exception is raised when an arithmetic operation produces a value exceeding maximum numeric representation bounds?

a) BoundError
b) OverflowError
c) MemoryError
d) LimitError
Correct Answer: b) OverflowError
Explanation:
OverflowError is raised when arithmetic calculation results exceed representable limits.

58. Which built-in module provides traceback.format_exc() to format the current exception traceback as a string?

a) sys
b) traceback
c) logging
d) inspect
Correct Answer: b) traceback
Explanation:
traceback.format_exc() returns the formatted stack trace string of the active exception.

59. What exception is raised when invoking list.index(val) for a value not present in the list?

a) IndexError
b) ValueError
c) KeyError
d) NotFoundError
Correct Answer: b) ValueError
Explanation:
list.index(x) raises 'ValueError: x is not in list' if the element is not found.

60. What exception is raised when calling dict.pop(key) without a default argument for a missing key?

a) IndexError
b) KeyError
c) ValueError
d) AttributeError
Correct Answer: b) KeyError
Explanation:
dict.pop(key) raises KeyError if key is missing and no default return value is specified.

61. What is returned by dict.pop(key, None) when key is missing from dictionary?

a) Raises KeyError
b) Returns None without raising an exception
c) Raises ValueError
d) Returns False
Correct Answer: b) Returns None without raising an exception
Explanation:
Providing a default argument to dict.pop() prevents KeyError and returns the default.

62. Which warning category is designed for end-users of Python applications rather than software developers?

a) DeprecationWarning
b) FutureWarning
c) SyntaxWarning
d) UserWarning
Correct Answer: b) FutureWarning
Explanation:
FutureWarning targets end-users about upcoming behavioral changes in packages.

63. Which warning category is intended specifically for developers regarding features planned for deprecation?

a) DeprecationWarning
b) FutureWarning
c) RuntimeWarning
d) UserWarning
Correct Answer: a) DeprecationWarning
Explanation:
DeprecationWarning is directed at developers to signal deprecated code usage.

64. How can warnings be turned into fatal runtime exceptions using command-line arguments when launching Python?

a) python -W error script.py
b) python -W fatal script.py
c) python --strict script.py
d) python -e warnings script.py
Correct Answer: a) python -W error script.py
Explanation:
Passing '-W error' instructs the Python warnings filter to elevate warnings to exceptions.

65. Which context manager in the warnings module temporarily isolates warning filters?

a) warnings.catch_warnings()
b) warnings.isolate()
c) warnings.suppress()
d) warnings.filter_scope()
Correct Answer: a) warnings.catch_warnings()
Explanation:
warnings.catch_warnings() copies and restores warning filters upon exiting the context.

66. What is the effect of calling logging.exception(msg) inside an except block?

a) Logs an ERROR message and automatically appends exception traceback info
b) Clears the active exception from stack
c) Reraises the exception automatically
d) Converts exception into warning level
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().

67. Which exception is raised when trying to slice a set object (e.g. s = {1, 2, 3}; s[0:2])?

a) IndexError
b) TypeError
c) KeyError
d) SliceError
Correct Answer: b) TypeError
Explanation:
Sets are unindexed collections; subscript slicing raises 'TypeError: 'set' object is not subscriptable'.

68. What exception is raised by math.factorial(-5)?

a) OverflowError
b) ValueError
c) TypeError
d) DomainError
Correct Answer: b) ValueError
Explanation:
Factorials are only defined for non-negative integers; negative numbers produce ValueError.

69. What exception is raised by math.factorial(3.5)?

a) ValueError
b) TypeError
c) FloatError
d) ArithmeticError
Correct Answer: a) ValueError
Explanation:
math.factorial requires integral values and raises ValueError when given floats with non-zero fractional parts.

70. What exception is raised when trying to remove an item from an empty deque using collections.deque.pop()?

a) KeyError
b) IndexError
c) ValueError
d) EmptyError
Correct Answer: b) IndexError
Explanation:
Popping from an empty deque raises 'IndexError: pop from an empty deque'.

71. What exception is raised by non-blocking queue.Queue.get_nowait() when invoked on an empty queue?

a) IndexError
b) queue.Empty
c) StopIteration
d) ValueError
Correct Answer: b) queue.Empty
Explanation:
queue.Queue.get_nowait() raises queue.Empty exception when no elements are available.

72. What exception is raised by non-blocking queue.Queue.put_nowait() when invoked on a full bounded queue?

a) OverflowError
b) queue.Full
c) MemoryError
d) BufferError
Correct Answer: b) queue.Full
Explanation:
queue.Queue.put_nowait() raises queue.Full exception when max size is reached.

73. Which exception is raised when str.encode() encounters an unknown encoding codec name?

a) UnicodeEncodeError
b) LookupError
c) ValueError
d) CodecError
Correct Answer: b) LookupError
Explanation:
Passing an invalid encoding name to encode() raises 'LookupError: unknown encoding'.

74. Which built-in exception is raised when an integer conversion via int.to_bytes() cannot fit in specified byte length?

a) ValueError
b) OverflowError
c) TypeError
d) RangeError
Correct Answer: b) OverflowError
Explanation:
int.to_bytes() raises OverflowError if integer magnitude exceeds specified output length.

75. What exception is raised when multiplying a list by a float (e.g., [1, 2] * 1.5)?

a) ValueError
b) TypeError
c) FloatError
d) ArithmeticError
Correct Answer: b) TypeError
Explanation:
Sequence repetition requires integer multipliers; floats raise 'TypeError: can't multiply sequence by non-int of type 'float''.

76. What exception is raised when positional formatting specifiers exceed provided positional arguments (e.g. '{0} {1}'.format('a'))?

a) KeyError
b) IndexError
c) ValueError
d) FormatError
Correct Answer: b) IndexError
Explanation:
Missing positional format arguments raise 'IndexError: Replacement index out of range'.

77. What exception is raised when named format placeholders are missing key arguments (e.g. '{val}'.format())?

a) KeyError
b) IndexError
c) NameError
d) ValueError
Correct Answer: a) KeyError
Explanation:
Missing keyword format arguments raise KeyError for the missing placeholder key.

78. What exception is raised when creating a class with conflicting metaclasses?

a) ClassError
b) TypeError
c) MetaclassError
d) InheritanceError
Correct Answer: b) TypeError
Explanation:
Incompatible metaclass inheritance hierarchies trigger 'TypeError: metaclass conflict'.

79. What exception is raised when os.kill() is passed a non-existent process ID (PID)?

a) ProcessLookupError
b) PIDError
c) FileNotFoundError
d) SystemError
Correct Answer: a) ProcessLookupError
Explanation:
ProcessLookupError (a subclass of OSError) is raised when target PID is not found.

80. What exception is raised when attempting to write to a read-only stream buffer handle?

a) ReadOnlyError
b) io.UnsupportedOperation
c) PermissionError
d) ModeError
Correct Answer: b) io.UnsupportedOperation
Explanation:
io.UnsupportedOperation (inheriting from ValueError and OSError) is raised when performing unsupported stream operations.

81. What exception occurs when sys.exit(0) is executed?

a) SystemError
b) SystemExit
c) ExitException
d) RuntimeError
Correct Answer: b) SystemExit
Explanation:
sys.exit() raises SystemExit exception, which can be caught if clean termination handling is needed.

82. What is stored in the 'code' attribute of a caught SystemExit exception 'e' when sys.exit(42) is called?

a) e.code == 42
b) e.status == 42
c) e.args[0] == '42'
d) e.exit_code == 42
Correct Answer: a) e.code == 42
Explanation:
SystemExit objects store the exit status code integer in their 'code' attribute.

83. What occurs if an exception is raised inside a generator's __del__ or close method during garbage collection?

a) It crashes the Python main thread
b) It is written to sys.unraisablehook / stderr and ignored
c) It is automatically converted to StopIteration
d) It causes a MemoryError
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.

84. Which exception is raised when struct.pack receives an argument incompatible with format layout specifiers?

a) struct.error
b) ValueError
c) TypeError
d) PackError
Correct Answer: a) struct.error
Explanation:
The standard struct module raises struct.error on packing or unpacking failures.

85. Which exception is raised when pickle.loads encounters corrupted or truncated binary data?

a) pickle.UnpicklingError
b) TypeError
c) ValueError
d) MemoryError
Correct Answer: a) pickle.UnpicklingError
Explanation:
The pickle module raises pickle.UnpicklingError when unpickling invalid data streams.

86. What error is raised when passing an invalid flag string to open() (e.g. open('file.txt', 'z'))?

a) IOError
b) ValueError
c) ModeError
d) OSError
Correct Answer: b) ValueError
Explanation:
open() raises 'ValueError: invalid mode' for unknown mode flag characters.

87. Which exception is raised when socket operations exceed configured timeout durations?

a) socket.timeout
b) NetworkError
c) HTTPError
d) ConnectionRefusedError
Correct Answer: a) socket.timeout
Explanation:
socket.timeout (an alias for TimeoutError) is raised when socket read/write calls time out.

88. Which exception is raised when trying to connect to a server port where no listener exists?

a) ConnectionRefusedError
b) ConnectionResetError
c) ConnectionAbortedError
d) BrokenPipeError
Correct Answer: a) ConnectionRefusedError
Explanation:
ConnectionRefusedError is raised when the target socket connection is rejected.

89. Which exception is raised when writing to a socket or pipe whose read end is closed?

a) ConnectionResetError
b) BrokenPipeError
c) EOFError
d) PipeError
Correct Answer: b) BrokenPipeError
Explanation:
BrokenPipeError is raised when attempting to write to a pipe/socket with no active reader.

90. What exception is raised when ast.parse encounters code with syntax errors?

a) ValueError
b) SyntaxError
c) ast.ASTError
d) TypeError
Correct Answer: b) SyntaxError
Explanation:
ast.parse raises SyntaxError when parsing invalid Python code.

91. What attribute of a caught SyntaxError holds the column offset of the error location?

a) e.column
b) e.offset
c) e.position
d) e.index
Correct Answer: b) e.offset
Explanation:
SyntaxError instances store the 1-based character offset index in the 'offset' attribute.

92. Which exception is raised when compile() receives source strings containing null bytes?

a) NullByteError
b) ValueError
c) SyntaxError
d) TypeError
Correct Answer: b) ValueError
Explanation:
compile() raises ValueError if embedded null bytes exist in the source string.

93. Which function allows configuring custom handling for unraisable exceptions in Python 3.8+?

a) sys.unraisablehook
b) sys.excepthook
c) traceback.unraisable
d) builtins.error_hook
Correct Answer: a) sys.unraisablehook
Explanation:
sys.unraisablehook allows customizing output when exceptions occur in contexts where they cannot be raised (e.g. __del__).

94. What is the return type of traceback.format_exception(e)?

a) A single string
b) A list of strings representing stack trace lines
c) A dictionary of frame objects
d) A tuple of numbers
Correct Answer: b) A list of strings representing stack trace lines
Explanation:
traceback.format_exception returns a list of formatted line strings.

95. What exception is raised when attempting to unpack a single non-iterable value (e.g., x, y = 5)?

a) ValueError
b) TypeError
c) UnpackError
d) IndexError
Correct Answer: b) TypeError
Explanation:
Unpacking a non-iterable object raises 'TypeError: cannot unpack non-iterable int object'.

96. What exception is raised when trying to append to a tuple (e.g. t = (1, 2); t.append(3))?

a) AttributeError
b) TypeError
c) ValueError
d) MutationError
Correct Answer: a) AttributeError
Explanation:
Tuples do not possess an append method, raising AttributeError.

97. What exception is raised by bytes.fromhex() when supplied with an odd-length hex string?

a) HexError
b) ValueError
c) TypeError
d) LengthError
Correct Answer: b) ValueError
Explanation:
Hex decoding requires complete byte pairs; odd-length strings raise ValueError.

98. What exception is raised when calling signal.signal() from a secondary thread in Python?

a) ThreadError
b) ValueError
c) SignalError
d) PermissionError
Correct Answer: b) ValueError
Explanation:
Signal handlers can only be set from the main thread; calling signal.signal() from subthreads raises ValueError.

99. What happens when an exception is raised inside a generator expression passed to any() or all()?

a) The function returns False
b) The exception propagates immediately out of the function call
c) The exception is caught and treated as True
d) StopIteration is returned
Correct Answer: b) The exception propagates immediately out of the function call
Explanation:
Exceptions occurring during lazy generator evaluation inside built-ins propagate immediately.

100. What error is raised when delattr(obj, 'attr') is executed for a non-existent attribute name?

a) NameError
b) AttributeError
c) KeyError
d) DeleteError
Correct Answer: b) AttributeError
Explanation:
Deleting non-existent object attributes raises AttributeError.

101. What exception is raised when os.rmdir() is called on a directory that is not empty?

a) DirectoryNotEmptyError
b) OSError
c) PermissionError
d) FileExistsError
Correct Answer: b) OSError
Explanation:
os.rmdir on non-empty directories raises OSError (specifically ENOTEMPTY).

102. What exception is raised when exec() receives a string containing invalid Python code?

a) ExecError
b) SyntaxError
c) ValueError
d) TypeError
Correct Answer: b) SyntaxError
Explanation:
exec() parses code strings dynamically and raises SyntaxError if syntax rules are violated.

103. What exception is raised when attempting to mutate an immutable range object (e.g. r = range(5); r[0] = 1)?

a) ValueError
b) TypeError
c) IndexError
d) AttributeError
Correct Answer: b) TypeError
Explanation:
range objects are immutable; item assignment raises 'TypeError: 'range' object does not support item assignment'.

104. Which of the following best describes exception safety in Python?

a) Preventing all exceptions from occurring at runtime
b) Ensuring system state remains consistent and resources are properly cleaned up even when exceptions occur
c) Wrapping all functions in bare try-except blocks
d) Disabling garbage collection during error handling
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.
← Previous: Python Functions MCQs
Next →: Python List Comprehension MCQs
Java Interfaces and Abstract Classes MCQs

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…

By MCQs Generator
Python Modules & Packages MCQs

Python Modules & Packages MCQs

Python modules are single files containing Python code (functions, classes, and variables) that can be imported and reused across different…

By MCQs Generator
Python Exception / Error Handling MCQs

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

By MCQs Generator