CCNA Exceptions File Io Questions

75 of 80 questions · Page 1/2 · Exceptions File Io topic · Answers revealed

1
MCQhard

A developer implements a custom exception class `DataError` that inherits from `Exception`. Which method override is essential to ensure the exception message is properly displayed when caught?

A.Override __init__ to accept a message and call super().__init__(message).
B.Set the __cause__ attribute in __init__.
C.Override __str__ to return a formatted string.
D.Override __repr__ to return a detailed representation.
AnswerA

This ensures the message is stored and displayed.

Why this answer

Option A is correct because the `Exception` class's `__init__` method stores the message argument in the `args` attribute, which is used by the default `__str__` method to display the message. By overriding `__init__` to accept a message and call `super().__init__(message)`, the custom exception properly passes the message to the base class, ensuring it is displayed when caught and printed.

Exam trap

Python Institute often tests the misconception that you must override `__str__` to display a custom message, when in fact the base `Exception.__init__` handles message storage and display automatically if called correctly.

How to eliminate wrong answers

Option B is wrong because setting the `__cause__` attribute is used for chaining exceptions (e.g., raising a new exception while preserving the original), not for setting the exception message. Option C is wrong because overriding `__str__` is not essential; the default `__str__` inherited from `Exception` already returns the message stored in `self.args`, so a custom `__str__` is only needed for special formatting. Option D is wrong because overriding `__repr__` affects the developer-facing representation (e.g., in the interactive shell), not the message displayed when the exception is caught and printed.

2
MCQeasy

A programmer needs to write a function that reads a large binary file (over 1 GB) and returns its entire content as a bytes object. The function must handle the case where the path provided is actually a directory (IsADirectoryError) by returning an empty bytes object. Which implementation is most memory-efficient and correctly handles the directory case? Consider that reading the entire file into memory is acceptable for the business case.

A.Use 'with open(path, 'rb') as f: return f.read()' inside a try-except IsADirectoryError catch that returns b''.
B.Use 'with open(path, 'rb') as f: return f.read()' inside a try-except OSError that returns b''.
C.Use os.path.isfile(path) to check before opening; if not a file, return b''.
D.Use 'with open(path, 'rb') as f: return [chunk for chunk in iter(lambda: f.read(1024), b'')]' inside a try-except IsADirectoryError.
AnswerA

Correctly handles the directory case, and .read() returns bytes.

Why this answer

Option A is correct because it uses a try-except block specifically catching `IsADirectoryError`, which is raised when `open()` is called on a directory path. The `with` statement ensures the file is properly closed, and `f.read()` returns the entire content as a bytes object, which is memory-efficient for this use case (the file is read in one large allocation, avoiding overhead from chunking).

Exam trap

Python Institute often tests the distinction between catching a specific exception (`IsADirectoryError`) versus a broad parent class (`OSError`), and the misconception that a pre-check like `os.path.isfile()` is safer than exception handling, ignoring the TOCTOU race condition.

How to eliminate wrong answers

Option B is wrong because catching `OSError` is too broad; it would suppress legitimate errors like permission denied or disk full, masking bugs. Option C is wrong because `os.path.isfile()` introduces a race condition (TOCTOU) — the file could be replaced by a directory between the check and the open, and it does not handle the case where the path is a directory that is later opened. Option D is wrong because it reads the file in 1024-byte chunks and collects them into a list, which is less memory-efficient than a single `f.read()` (the list overhead and multiple allocations waste memory), and it still catches `IsADirectoryError` correctly but is not the most memory-efficient.

3
MCQmedium

Refer to the exhibit. What is the output of the code?

A.None
B.False
C.True
D.Error
AnswerC

The file is explicitly closed.

Why this answer

After closing the file, file.closed returns True.

4
MCQeasy

Which method of a file object reads the entire content of a text file as a single string?

A.readall()
B.read()
C.readline()
D.readlines()
AnswerB

Returns the entire file as a string.

Why this answer

The `read()` method, when called without arguments or with a negative size, reads the entire contents of a file as a single string. This is the standard Python file object method for reading all text at once, returning a str object. It is the correct choice because the question explicitly asks for a method that returns the entire content as a single string.

Exam trap

Python Institute often tests the distinction between `read()` (returns a single string) and `readlines()` (returns a list of strings), causing candidates to confuse the two methods when the question specifies 'as a single string'.

How to eliminate wrong answers

Option A is wrong because `readall()` is not a valid method of a Python file object; it does not exist in the standard file I/O API. Option C is wrong because `readline()` reads only the next line from the file, returning a single string that ends with a newline character, not the entire content. Option D is wrong because `readlines()` reads all lines and returns them as a list of strings, each representing one line, not as a single concatenated string.

5
MCQmedium

Refer to the exhibit. What is the output of the code?

A.Error
B.True
C.False
D.None
AnswerC

Inside the with block, the file is still open.

Why this answer

The 'with' statement ensures the file is closed after the block, but inside the block the file is still open, so f.closed returns False.

6
MCQmedium

A company runs a data processing pipeline that reads CSV files from a network drive. Occasionally, the network drive is unreachable causing FileNotFoundError. The current code uses a bare except clause that catches all exceptions, which also masks programming errors like NameError. The lead developer wants to implement a more robust exception handling strategy. The requirement is to log the specific error (including the filename) and retry the operation up to 3 times with a 2-second delay between retries. If after 3 attempts the file is still inaccessible, the pipeline should skip the file and continue with the next one. Which approach best meets these requirements?

A.Use os.path.exists before opening the file, and if it returns False, log and skip.
B.Use a try-except block catching OSError, with a retry loop that logs the error and continues after max retries.
C.Use a try-except block catching Exception, with a retry loop and logging.
D.Use a with statement; if an exception occurs, call the function recursively up to 3 times.
AnswerB

Correctly catches I/O errors, implements retry, and logs specifically.

Why this answer

Option B is correct because it catches OSError, which is the parent class for file-related errors like FileNotFoundError, while still allowing programming errors like NameError to propagate. The retry loop with a 2-second delay and a maximum of 3 attempts satisfies the requirement, and after exhausting retries, the loop naturally continues to the next file, skipping the problematic one.

Exam trap

Python Institute often tests the distinction between catching OSError (specific to file/OS errors) versus Exception (which catches everything including NameError), and candidates mistakenly choose the broader catch because they think 'all exceptions' includes file errors, ignoring the requirement to not mask programming errors.

How to eliminate wrong answers

Option A is wrong because using os.path.exists before opening introduces a TOCTOU (time-of-check-time-of-use) race condition; the file could be deleted or become unavailable between the check and the open call, and it does not handle other OSError subtypes like PermissionError. Option C is wrong because catching Exception is too broad and will mask programming errors such as NameError or TypeError, which violates the requirement to avoid masking such errors. Option D is wrong because recursive calls risk hitting Python's recursion limit (default 1000) and do not provide a clean retry loop with delay; also, the with statement does not inherently handle retries or logging.

7
MCQhard

If the file 'log_output.txt' contains the lines shown, what is the actual output?

A.ERROR
B.ERROR: Disk full
C.INFO: Process started\nERROR: Disk full
D.ERROR: Disk full\nWARN: Memory high
AnswerB

Correct: only line with 'ERROR' is printed.

Why this answer

Option B is correct because the code likely uses a try-except block that catches an exception and prints 'ERROR: Disk full' to the file. The question states that the file contains the lines shown, and the actual output is the content written to the file, which matches 'ERROR: Disk full' exactly. The other options include additional lines or different formatting that do not appear in the given file content.

Exam trap

Python Institute often tests the distinction between the content written to a file and the representation of that content when read back, leading candidates to confuse the actual file content with formatted output that includes escape sequences like '\n'.

How to eliminate wrong answers

Option A is wrong because the file contains a line, not just the word 'ERROR', so the output is not simply 'ERROR'. Option C is wrong because the file does not contain two separate lines 'INFO: Process started' and 'ERROR: Disk full'; only one line is present. Option D is wrong because the file does not contain 'WARN: Memory high' as a second line; the output is only the single line 'ERROR: Disk full'.

8
MCQmedium

A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?

A.def safe_divide(a, b): try: return a/b except ZeroDivisionError: return None
B.def safe_divide(a, b): return a/b if b else None
C.def safe_divide(a, b): if b != 0: return a/b else: return None
D.def safe_divide(a, b): try: return a/b except ValueError: return None
AnswerA

Correct: EAFP approach with specific exception.

Why this answer

Option A is correct because it uses a try-except block to catch the specific ZeroDivisionError that Python raises when dividing by zero. This is the most Pythonic approach, following the EAFP (Easier to Ask for Forgiveness than Permission) principle, which is preferred over LBYL (Look Before You Leap) in Python. The function returns None only when the exception occurs, preserving the natural behavior of division for all other cases.

Exam trap

Python Institute often tests the distinction between EAFP and LBYL, and the trap here is that candidates may choose Option C (LBYL) because it appears safer, or Option D because they confuse ValueError with ZeroDivisionError, not realizing that Python raises a specific exception for division by zero.

How to eliminate wrong answers

Option B is wrong because it uses a conditional expression that evaluates b as a truthy value, which fails for non-numeric zero-like values (e.g., 0.0, 0j) and does not handle cases where b is a non-zero value that causes a different exception (e.g., string division). Option C is wrong because it implements LBYL (Look Before You Leap) by checking b != 0 before dividing, which is less Pythonic than EAFP and duplicates the check that the exception mechanism handles more cleanly. Option D is wrong because it catches ValueError, which is not raised by division by zero; the correct exception is ZeroDivisionError, so this implementation would let the ZeroDivisionError propagate unhandled.

9
Multi-Selectmedium

Which TWO statements about exception handling in Python are correct? (Select exactly 2.)

Select 2 answers
A.A single except clause can catch multiple exception types by passing a tuple of exceptions.
B.The order of except clauses does not matter because only one will match.
C.The finally block always executes, even if the try block contains a return statement.
D.An else block can be used without any except blocks in a try statement.
E.The else block in a try statement executes only if an exception was raised.
AnswersA, C

Yes, e.g., except (ValueError, TypeError):

Why this answer

Option A is correct because Python's except clause accepts a tuple of exception types, allowing a single handler to catch multiple exception types. For example, `except (ValueError, TypeError):` will catch either exception, which is a concise way to handle related errors without duplicating code.

Exam trap

Python Institute often tests the misconception that the else block runs after an exception or that except order is irrelevant, leading candidates to select B or E instead of recognizing the correct behavior of tuple-based except clauses and the unconditional execution of finally.

10
Matchingmedium

Match each Python data structure to its mutability.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Mutable

Immutable

Mutable

Immutable

Mutable

Why these pairings

Mutability of built-in data structures.

11
MCQhard

What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')

A.error done
B.done error
C.error
D.done
AnswerA

Correct order.

Why this answer

Option A is correct because the `exec('1/0')` raises a `ZeroDivisionError`, which is caught by the bare `except:` clause, printing 'error'. The `else` clause is skipped because an exception occurred, but the `finally` clause always executes, printing 'done'. Thus the output is 'error' followed by 'done'.

Exam trap

Python Institute often tests the order of execution in exception handling, specifically that `finally` always runs after `except` (not before), and that `else` is skipped when an exception occurs, causing candidates to misorder the output or forget the `finally` block.

How to eliminate wrong answers

Option B is wrong because it suggests 'done' prints before 'error', but the `except` block runs before the `finally` block, so the order is 'error' then 'done'. Option C is wrong because it omits the `finally` block output entirely, but `finally` always executes regardless of exceptions. Option D is wrong because it omits the 'error' output, but the exception is caught and 'error' is printed.

12
MCQeasy

A developer writes a script that opens a file for reading. The script must ensure that the file is closed even if an exception occurs during reading. Which pattern guarantees proper resource cleanup?

A.file = open('data.txt'); try: # read; finally: file.close()
B.file = open('data.txt'); # read; file.close()
C.with open('data.txt') as file: # read
D.file = open('data.txt'); if not file.closed: file.close()
AnswerC

Context manager guarantees close on exception or normal exit.

Why this answer

The 'with' statement (context manager) ensures the file is closed automatically when the block exits, even on exceptions. Option B uses 'with open'. Other options: manually using try/finally also works, but 'with' is recommended.

Option B is simplest and correct.

13
MCQmedium

A developer has a function that performs several operations and may raise different exceptions. The developer wants to catch a specific exception and then re-raise it after logging. Which code snippet correctly re-raises the same exception without losing its traceback?

A.except ValueError as e: log.error(e); raise
B.except ValueError as e: log.error(e); return None
C.except ValueError as e: log.error(e); raise ValueError('New')
D.except ValueError as e: log.error(e); pass
AnswerA

Re-raises the same exception preserving traceback.

Why this answer

Option A is correct because using a bare `raise` statement inside an `except` block re-raises the original exception instance, preserving its full traceback. This is the standard Python idiom for logging an exception and then propagating it unchanged, ensuring that the original call stack and error context are not lost.

Exam trap

Python Institute often tests the distinction between a bare `raise` (which preserves the original exception and traceback) and `raise SomeException(...)` (which creates a new exception and loses the original context), leading candidates to incorrectly choose the latter when they think they need to 're-raise' by specifying the exception class again.

How to eliminate wrong answers

Option B is wrong because `return None` does not re-raise the exception; it silently swallows the error and returns `None`, which changes the function's behavior and loses the exception entirely. Option C is wrong because `raise ValueError('New')` creates a brand-new exception instance, discarding the original exception's traceback and potentially its type or message, which breaks the requirement to re-raise the same exception. Option D is wrong because `pass` does nothing, causing the exception to be caught and then ignored (the `except` block ends without re-raising), effectively suppressing the error.

14
Multi-Selecthard

Which THREE of the following exception types are subclasses of OSError in Python 3?

Select 3 answers
A.FileNotFoundError
B.IOError
C.UnicodeError
D.PermissionError
E.EOFError
AnswersA, B, D

A subclass of OSError.

Why this answer

FileNotFoundError is a direct subclass of OSError, raised when a file or directory is requested but does not exist at the given path. This is part of Python's exception hierarchy for operating system-related errors, specifically for file operations that fail due to missing resources.

Exam trap

Python Institute often tests the misconception that IOError is a separate exception type in Python 3, when in fact it is an alias for OSError, and that UnicodeError or EOFError belong to the OSError family, which they do not.

15
MCQmedium

Refer to the exhibit. A developer is writing a script to read this JSON configuration file. The script should write the logging configuration to a separate file called 'logging.conf'. Which file mode should be used to create the file if it doesn't exist, and overwrite it if it does?

A.'x'
B.'r+'
C.'a'
D.'w'
AnswerD

Mode 'w' opens for writing, truncating existing file or creating new one.

Why this answer

Option D ('w') is correct because the 'w' mode opens a file for writing, truncating it first if it exists, and creating it if it does not. This matches the requirement to overwrite an existing 'logging.conf' file or create a new one if absent.

Exam trap

Python Institute often tests the distinction between 'w' and 'x' modes, where candidates mistakenly choose 'x' thinking it creates a new file, forgetting that 'x' raises an error if the file already exists, thus failing the overwrite requirement.

How to eliminate wrong answers

Option A ('x') is wrong because 'x' is an exclusive creation mode that raises a FileExistsError if the file already exists, so it cannot overwrite an existing file. Option B ('r+') is wrong because 'r+' opens a file for reading and writing but does not create the file if it does not exist; it raises a FileNotFoundError. Option C ('a') is wrong because 'a' opens a file for appending, which does not overwrite existing content; it writes new data at the end of the file.

16
MCQmedium

What will be printed?

A.-1
B.0
C.An exception is raised.
D.None
AnswerD

Correct: ValueError caught, returns None.

Why this answer

The code attempts to open a file for reading that does not exist, which raises a FileNotFoundError. Since the except clause only catches IOError, and FileNotFoundError is a subclass of OSError, not IOError (in Python 3), the exception is not caught. The program terminates with an unhandled exception, so nothing is printed, and the output is None.

Exam trap

Python Institute often tests the distinction between exception class hierarchies, specifically that FileNotFoundError is not caught by IOError in Python 3, leading candidates to incorrectly assume the exception is handled and some value is printed.

How to eliminate wrong answers

Option A is wrong because -1 is never printed; the code does not contain any print statement that would output -1, and the exception prevents any output. Option B is wrong because 0 is never printed; the code does not contain any print statement that would output 0, and the exception prevents any output. Option C is wrong because while an exception is raised, the question asks 'What will be printed?' and the answer is that nothing is printed (None), not that an exception is raised as the printed output.

17
MCQeasy

Which of the following statements about the `finally` block is true?

A.It executes only if no exception is raised.
B.It does not execute if a return statement is in try block.
C.It executes only if an exception is raised.
D.It always executes, regardless of exceptions.
AnswerD

Finally is guaranteed to run.

Why this answer

Option D is correct because the `finally` block in Python is designed to always execute after the `try` and `except` blocks, regardless of whether an exception was raised or not. This includes cases where a `return`, `break`, or `continue` statement is executed in the `try` block, or even if an unhandled exception occurs. The `finally` block is guaranteed to run before the function returns or the exception propagates, ensuring cleanup actions like closing files or releasing resources.

Exam trap

Python Institute often tests the misconception that a `return` statement in the `try` block prevents the `finally` block from executing, but in Python, the `finally` block always runs before the function returns, making this a common trap for candidates who confuse Python's behavior with that of other languages.

How to eliminate wrong answers

Option A is wrong because the `finally` block executes regardless of whether an exception is raised, not only when no exception occurs. Option B is wrong because the `finally` block does execute even if a `return` statement is in the `try` block; the `finally` block runs before the function actually returns. Option C is wrong because the `finally` block executes regardless of whether an exception is raised, not only when an exception occurs.

18
MCQmedium

A Python script that processes log files uses the following code: with open('log.txt', 'r') as f: lines = f.readlines() for line in lines: # process What is a potential inefficiency in this code?

A.The file is not properly closed after processing.
B.Reading the entire file into memory may be wasteful for large files.
C.Using readlines() is the most efficient way to iterate over lines.
D.The file should be opened in binary mode for better performance.
AnswerB

Correct: readlines() loads the whole file into memory.

Why this answer

Option B is correct because `readlines()` loads the entire file into memory as a list of strings. For large log files, this can consume significant memory and cause performance degradation or even memory errors. A more memory-efficient approach is to iterate directly over the file object (e.g., `for line in f:`), which reads one line at a time from disk.

Exam trap

Python Institute often tests the misconception that `readlines()` is the standard or recommended way to read a file line by line, when in fact the file object itself is an iterator that should be used for large files to avoid memory bloat.

How to eliminate wrong answers

Option A is wrong because the `with` statement ensures the file is automatically closed when the block exits, even if an exception occurs. Option C is wrong because `readlines()` is not the most efficient way to iterate over lines; it reads all lines into memory at once, whereas iterating over the file object directly is more memory-efficient. Option D is wrong because opening in binary mode (`'rb'`) would not improve performance for text log processing and would require manual decoding of bytes to strings, adding complexity without benefit.

19
MCQhard

A senior developer in a team argues that using try-except blocks is slower than checking conditions with if statements. They propose replacing all try blocks that handle file I/O errors with existence checks using os.path.exists before opening files. During a code review, you recall that Python's official documentation and best practices prefer EAFP (Easier to Ask for Forgiveness than Permission) over LBYL (Look Before You Leap) in many cases, especially in concurrent environments. The team's application is a multi-threaded web server that serves static files from a shared directory. Which is the strongest counterargument against the senior developer's proposal?

A.if statements are harder to read and maintain.
B.try-except can catch multiple exception types more cleanly.
C.try-except blocks have no performance cost at all.
D.LBYL leads to race conditions in concurrent code because the file's state can change between the check and the use.
AnswerD

This is the key flaw in the proposal for a multi-threaded server.

Why this answer

Option D is correct because in a multi-threaded web server, the LBYL approach (checking with os.path.exists) introduces a classic TOCTOU (Time of Check, Time of Use) race condition: between the existence check and the actual file open, another thread could delete or rename the file, causing the open to fail despite the check passing. Python's EAFP idiom (try-except) avoids this window by attempting the operation directly and handling the exception if it fails, which is inherently atomic with respect to the file system state. This is why official Python documentation recommends EAFP over LBYL in concurrent environments.

Exam trap

Python Institute often tests the misconception that try-except is purely about style or performance, when in reality the critical exam point is that LBYL introduces race conditions in concurrent code, making EAFP the safer and recommended pattern.

How to eliminate wrong answers

Option A is wrong because readability is subjective and not the strongest technical counterargument; if statements can be written clearly, and the core issue is correctness, not style. Option B is wrong because while try-except can catch multiple exception types cleanly, this is a convenience feature and does not address the fundamental race condition problem in concurrent file access. Option C is wrong because try-except blocks do have a small performance cost when an exception is raised (though negligible in I/O-bound code), but the claim that they have 'no performance cost at all' is factually incorrect and misses the point that the primary concern is correctness, not micro-optimization.

20
MCQmedium

Refer to the exhibit. Which of the following Python code snippets would generate this error?

A.int('abc')
B.str(123)
C.print('abc')
D.float('abc')
AnswerA

Attempts to convert 'abc' to int, causing ValueError.

Why this answer

Option A is correct because `int('abc')` attempts to convert the string `'abc'` to an integer, which is not a valid numeric literal. Python raises a `ValueError` with the message 'invalid literal for int() with base 10: 'abc''. This error occurs because the `int()` function expects a string that represents a valid integer in the specified base (default base 10), and 'abc' does not meet that criterion.

Exam trap

Python Institute often tests the exact wording of Python error messages, so the trap here is that candidates may confuse `ValueError` from `int()` with `ValueError` from `float()`, but the error message in the exhibit specifically cites 'invalid literal for int()', making only `int('abc')` the correct match.

How to eliminate wrong answers

Option B is wrong because `str(123)` successfully converts the integer 123 to the string '123', which is a valid operation and does not raise any error. Option C is wrong because `print('abc')` simply prints the string 'abc' to the standard output; it does not involve any type conversion that could raise a ValueError. Option D is wrong because `float('abc')` would also raise a ValueError, but the error message would be 'could not convert string to float: 'abc'', which is different from the specific error shown in the exhibit (which mentions 'invalid literal for int()').

The exhibit's error message explicitly references `int()` and base 10, so only `int('abc')` matches.

21
Multi-Selecteasy

Which TWO of the following are correct statements about the 'with' statement in Python file I/O?

Select 2 answers
A.It ensures the file is closed when the block exits.
B.It can only be used with file objects.
C.It automatically opens the file without needing open().
D.It ensures that resources are released even if an exception is raised.
E.It prevents any exception from occurring during file operations.
AnswersA, D

Correct: provides automatic cleanup.

Why this answer

Option A is correct because the 'with' statement in Python acts as a context manager that automatically calls the file object's __exit__ method when the block exits, which in turn invokes the file's close() method. This guarantees that the file is properly closed, even if an exception occurs within the block, ensuring deterministic resource cleanup.

Exam trap

Python Institute often tests the misconception that the 'with' statement is exclusive to file objects or that it automatically opens files, when in fact it is a general-purpose context manager that requires an already-opened resource and does not suppress exceptions.

22
MCQeasy

A developer writes a script to read a configuration file that may not exist. The script should handle the error gracefully and continue. Which approach is most Pythonic?

A.Use a try-except block catching FileNotFoundError
B.Use a try-except block catching OSError
C.Use os.path.exists to check, then open if it exists
D.Use an if statement to check file size
AnswerA

EAFP; clean and recommended for this scenario.

Why this answer

Option A is correct because it directly catches the specific `FileNotFoundError` exception, which is a subclass of `OSError` and is raised when a file does not exist. This approach follows the Pythonic principle of EAFP (Easier to Ask for Forgiveness than Permission), allowing the script to attempt the operation and handle the failure gracefully without redundant checks.

Exam trap

Python Institute often tests the distinction between catching a specific exception (`FileNotFoundError`) versus a broader parent exception (`OSError`), and the trap here is that candidates may choose the broader catch thinking it is safer, without realizing it can mask other critical errors.

How to eliminate wrong answers

Option B is wrong because catching `OSError` is too broad; it would also catch other operating system errors (e.g., permission denied, disk full) that may require different handling, masking the specific file-not-found scenario. Option C is wrong because using `os.path.exists` introduces a race condition (TOCTOU — Time of Check to Time of Use) where the file could be deleted or created between the check and the open call, and it violates the Pythonic EAFP idiom by using LBYL (Look Before You Leap). Option D is wrong because checking file size does not determine if a file exists; a file with zero size exists, and a non-existent file has no size to check, making this approach logically incorrect and unreliable.

23
Matchingmedium

Match each Python module to its purpose.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Mathematical functions

Generate pseudo-random numbers

Manipulate dates and times

Work with JSON data

Interact with operating system

Why these pairings

Common Python standard library modules.

24
MCQhard

Consider the code fragment: f = open('data.txt', 'r') data = f.read() process_data(data) f.close() What is the primary risk if an exception occurs during process_data(data)?

A.The file descriptor may be leaked because the close() call is skipped.
B.The exception will be silently suppressed.
C.The file will be automatically closed by Python's garbage collector immediately.
D.The file contents will be corrupted.
AnswerA

Correct: if an exception occurs, close() is not called.

Why this answer

Option A is correct because if `process_data(data)` raises an exception, the `f.close()` statement is never executed, leaving the file descriptor open. This is a resource leak that can exhaust system file handles, especially in long-running applications. Python's `with` statement is the recommended approach to guarantee automatic cleanup even when exceptions occur.

Exam trap

Python Institute often tests the misconception that Python's garbage collector immediately closes files, when in reality it only closes them during an unpredictable collection cycle, making explicit cleanup essential.

How to eliminate wrong answers

Option B is wrong because exceptions are not silently suppressed; they propagate up the call stack unless caught by an explicit `try-except` block. Option C is wrong because Python's garbage collector does not immediately close file descriptors; it may close them at an indeterminate time, and relying on it is poor practice and can lead to resource exhaustion. Option D is wrong because an exception during `process_data(data)` does not corrupt the file contents on disk; the file was opened in read mode, and the data is already read into memory before the exception occurs.

25
Multi-Selectmedium

Which TWO of the following are true about the 'with' statement in Python file I/O?

Select 2 answers
A.It can only be used with file objects
B.It is equivalent to a try/finally block
C.It automatically closes the file after the block
D.It does not require an __exit__ method
E.It requires the object to have an __enter__ method only
AnswersB, C

The 'with' statement ensures cleanup just like try/finally.

Why this answer

Option B is correct because the 'with' statement in Python is designed to simplify exception handling by encapsulating the setup and teardown of a resource in a context manager, which is functionally equivalent to a try/finally block. When you use 'with', the context manager's __exit__ method is guaranteed to be called even if an exception occurs, ensuring that cleanup actions like closing a file are performed, just as a finally clause would.

Exam trap

Python Institute often tests the misconception that the 'with' statement is only for file I/O, but the trap here is that candidates forget the context manager protocol requires both __enter__ and __exit__ methods, not just one, and that it applies to any object implementing that protocol.

26
MCQeasy

In Python, if you have a try block followed by an except clause that catches all exceptions, which of the following is true about the else clause?

A.The else clause runs only if no exception is raised in the try block.
B.The else clause runs only if an exception occurs.
C.The else clause runs before the finally block regardless of exceptions.
D.The else clause is used to specify additional exception handlers.
AnswerA

Correct: else executes when try block completes without exception.

Why this answer

In Python, the `else` clause in a `try` statement executes only if no exception was raised in the `try` block. This is true regardless of whether the `except` clause catches all exceptions (e.g., bare `except:` or `except Exception:`). The `else` block is specifically designed for code that should run only when the `try` block completes successfully without any exception.

Exam trap

The trap here is that candidates often confuse the `else` clause with a second chance to handle exceptions or think it runs unconditionally before `finally`, when in fact it is strictly tied to the successful execution of the `try` block and is skipped entirely if any exception occurs.

How to eliminate wrong answers

Option B is wrong because the `else` clause runs only when no exception occurs, not when an exception occurs; code that runs on an exception belongs in the `except` block. Option C is wrong because the `else` clause runs before the `finally` block only if no exception was raised, but if an exception is raised, the `else` block is skipped entirely and the `finally` block still runs; the order is not guaranteed to be `else` before `finally` in all cases. Option D is wrong because the `else` clause is not used to specify additional exception handlers; additional exception handlers are specified by additional `except` clauses, while the `else` clause is for code that executes only on successful completion of the `try` block.

27
MCQhard

You are a Python developer at a financial firm. Your team maintains a high-frequency trading system that reads real-time market data from a binary file 'market_feed.bin'. The file is updated every millisecond by an external process. Your script uses a `with` statement to open the file in binary read mode and reads exactly 1024 bytes each iteration in an infinite loop. Recently, the script has been crashing intermittently with an `OSError` with message '[Errno 9] Bad file descriptor'. The error occurs at random times, sometimes after minutes, sometimes after hours. The system runs on Linux. The script runs as a daemon. You suspect the issue is related to file descriptor exhaustion or the external process manipulating the file. What is the most likely cause and the best course of action?

A.Open the file without using a context manager and manually close it after each read.
B.Increase the read buffer size to 4096 bytes to reduce the number of read operations.
C.Catch OSError and re-open the file within the except block, then continue reading.
D.Use file locking (e.g., fcntl.flock) to coordinate access with the external process, and re-open the file if a lock cannot be acquired.
AnswerD

File locking prevents the external process from truncating the file while your script is reading, avoiding the bad file descriptor.

Why this answer

The most likely cause is that the external process overwrites or truncates 'market_feed.bin' between reads, causing the file descriptor held by the Python script to become invalid (stale). On Linux, when a file is replaced or truncated by another process, the original file descriptor may point to a deleted inode, and subsequent reads yield 'Bad file descriptor'. Option D is correct because file locking (e.g., fcntl.flock with LOCK_SH or LOCK_EX) coordinates access, and re-opening the file after a lock failure ensures a fresh, valid descriptor.

Exam trap

Python Institute often tests the misconception that catching and retrying an OSError (Option C) is sufficient, but the trap is that it ignores the underlying race condition and can lead to infinite loops or data corruption, whereas proper synchronization (Option D) prevents the error from occurring in the first place.

How to eliminate wrong answers

Option A is wrong because opening without a context manager and manually closing does not address the root cause—the external process invalidates the descriptor regardless of how it was opened. Option B is wrong because increasing the buffer size to 4096 bytes only reduces the number of read operations but does not prevent the descriptor from becoming stale; the error can still occur on the next read. Option C is wrong because catching OSError and re-opening within the except block is a reactive fix that does not prevent the race condition; it may also lead to infinite error loops if the external process continuously replaces the file.

28
MCQhard

Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?

A.Prints contents of backup.txt
B.Nothing
C.FileNotFoundError
D.'No file found'
AnswerD

Correct output from inner except.

Why this answer

Option D is correct because the code uses a try-except block to catch FileNotFoundError when attempting to open 'data.txt'. In the except block, it prints 'No file found' and then attempts to open 'backup.txt'. Since both files do not exist, the except block executes and prints 'No file found' before the second open attempt raises another FileNotFoundError, which is unhandled and terminates the program.

However, the question asks for the output, which is the print statement executed before the error.

Exam trap

Python Institute often tests the distinction between output produced before an unhandled exception and the exception itself, tricking candidates into thinking the program crashes without any output.

How to eliminate wrong answers

Option A is wrong because backup.txt does not exist, so its contents cannot be printed; the code would raise a FileNotFoundError on the second open attempt. Option B is wrong because the except block explicitly prints 'No file found' before the second open attempt, so something is output. Option C is wrong because while a FileNotFoundError does occur on the second open, the question asks for the output, not the exception; the print statement executes first, producing output.

29
MCQmedium

What is the output of the code?

A.Prints all lines in the file.
B.Raises an unhandled exception.
C.Prints all lines containing 'ERROR'
D.Error found: 2025-03-15 10:23:45 ERROR: Division by zero in module calc.py line 42
AnswerD

First ERROR line is raised and printed.

Why this answer

The code reads a log file line by line and checks if the line contains the substring 'ERROR'. When it finds the line '2025-03-15 10:23:45 ERROR: Division by zero in module calc.py line 42', it prints 'Error found: ' followed by that line. After printing, it breaks out of the loop, so only the first matching line is output.

Option D correctly describes this behavior.

Exam trap

Python Institute often tests the subtlety of the `break` statement inside a loop, leading candidates to mistakenly think all matching lines are printed instead of only the first.

How to eliminate wrong answers

Option A is wrong because the code does not print all lines; it only prints lines containing 'ERROR' and then breaks after the first match. Option B is wrong because no exception is raised; the file is opened with a context manager, read line by line, and the substring check is safe. Option C is wrong because although the code does print lines containing 'ERROR', it only prints the first such line (due to the break statement), not all of them.

30
MCQmedium

A function attempts to write to a file and needs to ensure the file is closed even if an exception occurs. Which code snippet guarantees closure?

A.f = open('file.txt', 'w'); f.write('data'); f.close()
B.with open('file.txt', 'w') as f: f.write('data')
C.f = open('file.txt', 'w'); try: f.write('data'); except: pass; f.close()
D.f = open('file.txt', 'w'); try: f.write('data'); finally: f.close()
AnswerB

Context manager ensures closure automatically.

Why this answer

Option A is correct because the 'with' statement provides a context manager that automatically closes the file, ensuring closure even if an exception occurs. Option B also guarantees closure but is less idiomatic. Option C does not handle exceptions.

Option D may not close on some exceptions.

31
MCQmedium

A Python script processes a log file line by line. If a line cannot be decoded due to an encoding error, the script should skip the line and continue. Which exception handling approach is best?

A.Wrap the entire file reading in a try-except block without specifying exception type.
B.Use a try-except-else block to handle success and failure separately, exiting on failure.
C.Inside the loop, wrap the line decoding in a try-except UnicodeDecodeError block and continue.
D.Catch Exception in the outer loop and break on error.
AnswerC

This isolates decoding issues and continues processing.

Why this answer

Option C is correct because it places the try-except block inside the loop, specifically catching `UnicodeDecodeError` for each line. This allows the script to skip only the problematic line and continue processing subsequent lines, which matches the requirement exactly.

Exam trap

Python Institute often tests the distinction between catching exceptions at the loop level versus the file level, and the trap here is that candidates choose a broad catch-all or an outer try-except that stops the loop, missing the requirement to skip only the problematic line and continue.

How to eliminate wrong answers

Option A is wrong because a bare `except:` clause catches all exceptions, including `KeyboardInterrupt` and `SystemExit`, which is poor practice and may hide critical errors; it also wraps the entire file reading, so any error would abort the loop entirely. Option B is wrong because it exits on failure, which contradicts the requirement to skip the line and continue; the `else` block runs only if no exception occurs, but the overall structure still stops on error. Option D is wrong because catching `Exception` in the outer loop and breaking on error would stop processing the entire file upon the first encoding error, rather than skipping just that line.

32
MCQmedium

A developer is writing a script that processes user-uploaded CSV files. The script should attempt to read the file, and if a UnicodeDecodeError occurs, log a warning and skip the file. Which code snippet correctly achieves this without stopping the entire process?

A.try: read_file() except (UnicodeDecodeError, OSError): pass
B.try: read_file() except UnicodeDecodeError: log.warning('Skipping file')
C.try: read_file() except Exception: log.warning('Skipping file')
D.try: read_file() except UnicodeEncodeError: log.warning('Skipping file')
AnswerB

Correctly catches only UnicodeDecodeError and continues with next file.

Why this answer

Option B is correct because it catches only UnicodeDecodeError, which is the specific exception raised when a file contains invalid UTF-8 or other encoding issues. It logs a warning and then continues execution (the 'pass' is implied by the log statement, but the key is that the exception is handled without re-raising). This matches the requirement to skip the file without stopping the entire process.

Exam trap

Python Institute often tests the distinction between UnicodeDecodeError (input decoding) and UnicodeEncodeError (output encoding), and the trap here is that candidates confuse the two or use an overly broad except clause that hides bugs.

How to eliminate wrong answers

Option A is wrong because it catches both UnicodeDecodeError and OSError, but uses 'pass' instead of logging a warning, which fails the requirement to log a warning. Option C is wrong because it catches the broad Exception class, which would suppress all exceptions (including critical ones like KeyboardInterrupt or SystemExit) and violates best practices by being too broad. Option D is wrong because it catches UnicodeEncodeError, which is raised when encoding output (e.g., writing to a file), not when reading/decoding input; the correct exception for reading is UnicodeDecodeError.

33
MCQhard

Which of the following correctly raises a new exception while preserving the original traceback?

A.raise original_exception
B.raise ValueError('new')
C.raise ValueError('new') from original_exception
D.raise
AnswerC

Correct chaining syntax.

Why this answer

Option C is correct because the `raise ... from original_exception` syntax in Python allows you to raise a new exception while chaining it to the original exception, preserving the original traceback. This is essential for debugging, as it shows both the new error and the root cause.

Exam trap

Python Institute often tests the distinction between re-raising the same exception (bare `raise` or `raise original_exception`) and raising a new exception with chaining (`raise ... from original_exception`), trapping candidates who think any `raise` preserves the traceback.

How to eliminate wrong answers

Option A is wrong because `raise original_exception` re-raises the exact same exception object, not a new one, so it does not create a new exception. Option B is wrong because `raise ValueError('new')` raises a brand-new exception without any reference to the original, losing the original traceback entirely. Option D is wrong because a bare `raise` can only be used inside an except block to re-raise the current exception; outside an except block it raises a RuntimeError, and it does not create a new exception.

34
MCQhard

Refer to the exhibit. The script stops with this error. Which exception type should be caught to handle this error gracefully?

A.ValueError
B.OSError
C.FileNotFoundError
D.IOError
AnswerB

FileNotFoundError inherits from OSError, so catching OSError handles it.

Why this answer

The error is FileNotFoundError, which is a subclass of OSError. Catching OSError or FileNotFoundError would handle it.

35
MCQhard

A developer is creating a custom exception hierarchy for a library. The base exception is `LibraryError`. Which definition ensures that subclasses can be caught using the parent exception, but also allows distinguishing between different error types?

A.class LibraryError: pass class FileError(LibraryError): pass class ParseError(LibraryError): pass
B.class LibraryError(BaseException): pass class FileError(LibraryError): pass class ParseError(LibraryError): pass
C.class LibraryError(Exception): pass class FileError(LibraryError): pass class ParseError(LibraryError): pass
D.class LibraryError(Exception): pass class FileError(Exception): pass class ParseError(Exception): pass
AnswerC

Standard practice: library base inherits from Exception, specific errors inherit from base.

Why this answer

Option C is correct because it defines `LibraryError` as a subclass of `Exception`, which is the proper base class for all user-defined exceptions in Python. Subclasses `FileError` and `ParseError` inherit from `LibraryError`, so they can be caught with `except LibraryError` while still being distinguishable by their own type. This follows the standard Python exception hierarchy, where custom exceptions should derive from `Exception`, not `BaseException` or no base class.

Exam trap

Python Institute often tests the distinction between `Exception` and `BaseException`, and the trap here is that candidates mistakenly think any class named 'Error' is automatically an exception, or they choose Option B thinking `BaseException` is the correct base for all custom exceptions.

How to eliminate wrong answers

Option A is wrong because `LibraryError` does not inherit from `Exception`; it is a plain class, so it cannot be caught by a standard `except Exception` clause and does not integrate with Python's exception handling mechanism. Option B is wrong because `LibraryError` inherits from `BaseException`, which is reserved for system-exiting exceptions like `SystemExit` and `KeyboardInterrupt`; catching `BaseException` is discouraged as it can suppress critical signals. Option D is wrong because `FileError` and `ParseError` both inherit directly from `Exception` rather than from `LibraryError`, so they cannot be caught collectively as `LibraryError` and break the intended hierarchy.

36
MCQeasy

Which of the following is the correct way to open a file for writing in binary mode?

A.open('data.dat', 'wb')
B.open('data.dat', 'bw')
C.open('data.dat', 'br')
D.open('data.dat', 'w')
AnswerA

Correctly opens for binary writing.

Why this answer

Option A is correct because the mode string 'wb' specifies both write ('w') and binary ('b') mode, which is the proper way to open a file for writing binary data in Python. The order of characters in the mode string is fixed: the file mode character ('r', 'w', 'a', etc.) must come first, followed by the optional 'b' for binary mode.

Exam trap

Python Institute often tests the strict ordering of mode characters in the open() function, expecting candidates to know that 'b' must always follow the read/write/append character, not precede it.

How to eliminate wrong answers

Option B is wrong because 'bw' reverses the required order — the mode character ('w') must precede the binary modifier ('b'), and Python will raise a ValueError for an invalid mode string. Option C is wrong because 'br' opens the file for reading in binary mode, not writing. Option D is wrong because 'w' opens the file for writing in text mode, not binary mode, which can cause data corruption when writing non-text data (e.g., images or serialized objects) due to newline translation.

37
Drag & Dropmedium

Drag and drop the steps to read a CSV file using the csv module in Python into the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Reading a CSV file requires importing csv, opening the file, creating a reader, iterating rows, and closing the file.

38
MCQmedium

A developer is building a logging system that writes logs to a file. The system should handle disk-full situations gracefully without crashing the main application. Which approach is appropriate?

A.Check disk space before each write; if low, skip logging.
B.Wrap the entire application in a try/except that catches all exceptions.
C.Let the OSError propagate to the main program's exception handler.
D.Wrap the log write in a try/except that catches OSError and writes to stderr as fallback.
AnswerD

Catches disk-full errors and logs to stderr, keeping app running.

Why this answer

Option D is correct because it uses a targeted try/except block around only the log write operation, catching OSError (which includes disk-full conditions) and falling back to stderr. This prevents the main application from crashing while still reporting the error, adhering to the principle of handling exceptions at the point where they occur and only when you can meaningfully recover.

Exam trap

Python Institute often tests the distinction between catching overly broad exceptions (Option B) versus catching specific exceptions (Option D), and the trap here is that candidates may think 'catching all exceptions' is a safe catch-all, but it actually hides programming errors and violates Python best practices.

How to eliminate wrong answers

Option A is wrong because checking disk space before each write is unreliable (race conditions, non-atomic check-then-act) and adds unnecessary overhead; it also does not handle other OSError scenarios like permission errors. Option B is wrong because wrapping the entire application in a blanket try/except that catches all exceptions (including KeyboardInterrupt, SystemExit) is an anti-pattern that masks bugs, violates the principle of catching specific exceptions, and can leave the application in an inconsistent state. Option C is wrong because letting OSError propagate to the main program's exception handler typically results in an unhandled exception that terminates the application, which is exactly what the developer wants to avoid.

39
Multi-Selectmedium

Which TWO of the following are valid ways to raise an exception in Python?

Select 2 answers
A.raise
B.raise Exception
C.throw ValueError('error')
D.raise Exception('error')
E.raise ValueError('invalid value')
AnswersD, E

Correct syntax to raise an exception with message.

Why this answer

Option D is correct because `raise Exception('error')` is the standard Python syntax to raise an exception with a custom message. The `raise` keyword is followed by an exception class (or instance), and passing a string argument provides an error message that is stored in the exception's `args` attribute. This is the most common and explicit way to raise an exception in Python.

Exam trap

Python Institute often tests the distinction between `raise` and `throw` to catch candidates who are familiar with other languages, and the fact that `raise` alone is only valid in an `except` block, not as a standalone statement.

40
Multi-Selecteasy

Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)

Select 2 answers
A.InputError
B.ValueError
C.DataError
D.FileNotFoundError
E.CustomError
AnswersB, D

ValueError is a built-in exception raised when a function gets an argument of correct type but inappropriate value.

Why this answer

ValueError is a built-in exception in Python, raised when a built-in operation or function receives an argument with the correct type but an inappropriate value, such as int('abc'). It is part of Python's standard exception hierarchy and does not require any import.

Exam trap

Python Institute often tests candidates by including plausible-sounding exception names like InputError or DataError that mimic real-world patterns but are not part of Python's built-in exception hierarchy, leading candidates to confuse custom or third-party exceptions with standard ones.

41
MCQhard

What is the output of the Python code after reading the config.txt file?

A.8080 (as string)
B.An exception is raised.
C.8080
D.'8080'
AnswerC

getint returns integer 8080.

Why this answer

The code reads the config.txt file and splits its content by newlines. The first line contains 'port=8080', and after splitting by '=', the second element is '8080'. The int() function converts this string to the integer 8080, which is then printed.

Option C is correct because the output is the integer 8080, not a string or quoted form.

Exam trap

The trap here is that candidates confuse the internal data type (string vs integer) with the printed output, assuming that because the source is a string, the output must also be a string or quoted, when in fact int() converts it to an integer and print() displays it without quotes.

How to eliminate wrong answers

Option A is wrong because the output is an integer, not a string; int() converts the string '8080' to an integer, so the printed value is 8080 without quotes. Option B is wrong because no exception is raised: the file is opened successfully, split operations are valid, and int('8080') is a valid conversion. Option D is wrong because the output is the integer 8080, not the string '8080' with quotes; print() outputs the integer representation without quotes.

42
MCQeasy

If the file 'config.json' exists but contains invalid JSON, what is printed?

A.Unexpected error
B.The program crashes with an unhandled exception.
C.Missing config file
D.Invalid JSON
AnswerD

Correct: JSONDecodeError is caught.

Why this answer

Option D is correct because the code explicitly catches `json.JSONDecodeError` (or `ValueError` in older Python versions) when parsing the file content. If the JSON is invalid, this exception is raised and caught by the `except (json.JSONDecodeError, ValueError)` block, which prints 'Invalid JSON'. The file exists, so the `except FileNotFoundError` block is not triggered.

Exam trap

Python Institute often tests the distinction between file existence errors (`FileNotFoundError`) and content parsing errors (`json.JSONDecodeError`), trapping candidates who assume any file problem results in a generic crash or a missing-file message.

How to eliminate wrong answers

Option A is wrong because 'Unexpected error' is not printed; the code has a specific handler for invalid JSON, not a generic catch-all. Option B is wrong because the program does not crash; the exception is caught, preventing an unhandled crash. Option C is wrong because 'Missing config file' is only printed if `FileNotFoundError` is raised, which requires the file to be absent, but the file exists (albeit with invalid content).

43
Multi-Selecthard

Which THREE of the following are true about Python's exception hierarchy?

Select 3 answers
A.KeyboardInterrupt inherits from BaseException.
B.SystemExit inherits from BaseException.
C.IOError is a separate class from OSError.
D.ZeroDivisionError inherits from ArithmeticError.
E.GeneratorExit inherits from Exception.
AnswersA, B, D

Correct: KeyboardInterrupt is under BaseException.

Why this answer

Option A is correct because `KeyboardInterrupt` inherits directly from `BaseException`, not from `Exception`. This design ensures that `KeyboardInterrupt` (raised by Ctrl+C) is not caught by a generic `except Exception:` clause, allowing the program to be interrupted even when broad exception handling is in place.

Exam trap

Python Institute often tests the misconception that `GeneratorExit` inherits from `Exception` (it actually inherits from `BaseException`), and that `IOError` is a separate class from `OSError` (it is an alias in Python 3).

44
MCQhard

When should you raise a specific exception class rather than a generic Exception?

A.When different error conditions require different handling.
B.Always raise Exception for simplicity.
C.Specific exceptions cannot be created; only built-in ones can be used.
D.Only when performance is a concern.
AnswerA

Correct: specific exceptions enable targeted handling.

Why this answer

Raising a specific exception class (e.g., ValueError, KeyError, or a custom subclass) allows the caller to catch and handle each error condition differently using separate except blocks. Using a generic Exception forces all errors into a single handler, which can mask distinct failure modes and make debugging harder. This aligns with Python's EAFP (Easier to Ask for Forgiveness than Permission) idiom, where precise exception types enable fine-grained error recovery.

Exam trap

Python Institute often tests the misconception that generic Exception is simpler or sufficient, but the trap is that it forces all errors into one catch-all, which hides the need for distinct handling logic and violates Pythonic best practices for exception granularity.

How to eliminate wrong answers

Option B is wrong because always raising generic Exception violates the principle of exception specificity, making it impossible for callers to distinguish between error types without inspecting the message string, which is fragile and discouraged. Option C is wrong because Python allows creation of custom exception classes by subclassing Exception (or any other built-in exception), enabling domain-specific error handling. Option D is wrong because performance is rarely a concern when choosing exception types; the decision should be based on semantic clarity and handling requirements, not optimization.

45
Multi-Selecthard

Which THREE of the following are true about the `with` statement for file handling?

Select 3 answers
A.It can only be used with files.
B.It can only handle one file at a time.
C.It uses the __enter__ and __exit__ methods of the file object.
D.It ensures the file is closed even if an exception occurs inside the block.
E.It automatically closes the file when the block exits.
AnswersC, D, E

These methods implement the context manager.

Why this answer

Option C is correct because the `with` statement relies on the context management protocol, which requires the object to implement the `__enter__` and `__exit__` methods. When a file object is used with `with`, its `__enter__` method returns the file object itself, and its `__exit__` method is called upon block exit to handle cleanup, such as closing the file.

Exam trap

Python Institute often tests the misconception that `with` is only for files, but the trap here is that candidates may also incorrectly think it can only handle one file at a time, while Python actually supports multiple context managers in a single `with` statement.

46
MCQmedium

A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?

A.File size
B.0
C.-1
D.10
AnswerD

Correctly reflects the new position.

Why this answer

Option D is correct because the `tell()` method returns the current position of the file pointer in bytes from the beginning of the file. After reading 10 characters (each being 1 byte in a typical text file), the pointer advances by 10 bytes, so `tell()` returns 10.

Exam trap

Python Institute often tests the misconception that `tell()` returns the number of characters read or the file size, when in fact it returns the byte offset from the start of the file.

How to eliminate wrong answers

Option A is wrong because `tell()` does not return the file size; it returns the current offset, not the total length. Option B is wrong because the file pointer moves after reading, so it cannot remain at 0. Option C is wrong because `tell()` never returns -1; it always returns a non-negative integer representing the byte offset.

47
Multi-Selecthard

Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)

Select 3 answers
A.It can be used with any object that implements __enter__ and __exit__ methods.
B.It guarantees that the __exit__ method is called even if an exception occurs inside the block.
C.It can be used with multiple context managers separated by commas.
D.It eliminates the need for try/finally blocks for resource management.
E.It can only be used with file objects.
AnswersA, B, C

That's the context manager protocol.

Why this answer

Option A is correct because the 'with' statement in Python is designed to work with any object that implements the context management protocol, which consists of the __enter__ and __exit__ methods. This allows the 'with' statement to manage resources beyond just files, such as database connections, locks, or network sockets, as long as the object provides these two methods.

Exam trap

Python Institute often tests the misconception that the 'with' statement is only for file I/O, leading candidates to incorrectly select option E, while also testing the understanding that it simplifies but does not replace try/finally blocks, making option D a distractor for those who overestimate its capabilities.

48
Drag & Dropmedium

Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Serialization to JSON involves importing json, preparing data, using dumps for string or dump for file output.

49
MCQmedium

A script uses `with open('data.bin', 'rb') as f:` to read binary data. Within the block, which method should be used to read exactly 4 bytes?

A.f.read(4)
B.f.seek(4)
C.f.readline()
D.f.read()
AnswerA

Reads up to 4 bytes.

Why this answer

The `read(n)` method reads exactly `n` bytes from the file object when the file is opened in binary mode (`'rb'`). Since the question specifies reading exactly 4 bytes, `f.read(4)` is the correct and direct approach. This method returns a bytes object of up to `n` bytes, but if the file has at least 4 bytes remaining, it will return exactly 4.

Exam trap

Python Institute often tests the distinction between `read()` (reads entire file), `read(n)` (reads exactly n bytes), and `seek()` (moves pointer without reading), and the trap here is that candidates may confuse `seek(4)` with reading 4 bytes, or assume `read()` without arguments reads a fixed number of bytes.

How to eliminate wrong answers

Option B is wrong because `f.seek(4)` moves the file pointer to byte offset 4 from the beginning, but does not read any data. Option C is wrong because `f.readline()` reads until a newline byte (`\n`) or EOF, which is not guaranteed to return exactly 4 bytes and is intended for text-based line reading, not fixed-size binary reads. Option D is wrong because `f.read()` with no argument reads the entire remaining contents of the file into memory, which will almost certainly not be exactly 4 bytes unless the file itself is exactly 4 bytes long.

50
MCQmedium

What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')

A.fin err
B.fin
C.err fin
D.err
AnswerC

Exception triggers except, then finally runs.

Why this answer

Option C is correct because when a division by zero occurs, Python raises a ZeroDivisionError, which is caught by the bare except clause, printing 'err'. The finally clause always executes after the except block, printing 'fin'. Thus the output is 'err' followed by 'fin'.

Exam trap

Python Institute often tests the order of execution in try/except/finally blocks, specifically that the except block runs before the finally block when an exception is caught, and that the finally block always executes even if no exception occurs.

How to eliminate wrong answers

Option A is wrong because it shows 'fin err', implying the finally block runs before the except block, but in Python the except block runs first when an exception is caught. Option B is wrong because it shows only 'fin', ignoring that the except block prints 'err' when the exception is caught. Option D is wrong because it shows only 'err', omitting the finally block which always executes regardless of whether an exception occurs or is caught.

51
MCQeasy

A developer writes a function that reads a file and processes its content. The function should handle the case where the file does not exist without catching other I/O errors. Which exception should be caught?

A.PermissionError
B.IOError
C.OSError
D.FileNotFoundError
AnswerD

FileNotFoundError is the specific exception for a missing file, ideal for this scenario.

Why this answer

Option D is correct because `FileNotFoundError` is a specific subclass of `OSError` that is raised exactly when a file or directory is requested but does not exist. By catching only `FileNotFoundError`, the function handles the missing-file scenario without masking other I/O errors such as permission issues or disk failures, which is the precise requirement stated in the question.

Exam trap

Python Institute often tests the Python exception hierarchy, and the trap here is that candidates mistakenly choose `IOError` or `OSError` because they are broader and seem 'safer,' but the question explicitly requires handling only the missing-file case without catching other I/O errors.

How to eliminate wrong answers

Option A is wrong because `PermissionError` is raised when the file exists but the process lacks the necessary permissions (e.g., read or write access), not when the file is missing. Option B is wrong because `IOError` is an alias for `OSError` in Python 3 and is too broad; catching it would also catch unrelated I/O errors like permission or disk errors, violating the requirement to avoid catching other I/O errors. Option C is wrong because `OSError` is the parent class for many file-related exceptions (including `FileNotFoundError`, `PermissionError`, etc.); catching it would handle all OS-level errors, not just the missing-file case.

52
MCQmedium

A developer wants to ensure that a file is always closed after writing, even if an exception occurs. Which approach is considered best practice in Python?

A.Use try/finally with explicit f.close()
B.Rely on the garbage collector to close the file
C.Use try/except/finally with f.close() in both except and finally
D.Use the with statement: with open('file.txt', 'w') as f: ...
AnswerD

Context manager ensures automatic cleanup.

Why this answer

Option D is correct because the `with` statement in Python implements a context manager that automatically calls the file's `__exit__` method, which closes the file even if an exception occurs inside the block. This is the idiomatic and recommended approach for resource management, as it guarantees cleanup without requiring explicit `close()` calls.

Exam trap

Python Institute often tests the misconception that `try/finally` with explicit `close()` is equivalent to the `with` statement, but the trap is that the `with` statement is the explicitly recommended best practice in the Python documentation and PEP 343, making it the correct answer over more manual approaches.

How to eliminate wrong answers

Option A is wrong because while `try/finally` with explicit `f.close()` does ensure the file is closed, it is more verbose and error-prone than the `with` statement, and it is not considered best practice in modern Python. Option B is wrong because relying on the garbage collector to close the file is unreliable — the garbage collector may not run immediately, and file descriptors are a limited OS resource that should be released deterministically. Option C is wrong because placing `f.close()` in both `except` and `finally` is redundant and unnecessary; the `finally` block alone guarantees execution regardless of exceptions, so duplicating the call in `except` adds no benefit and can lead to double-close errors if not handled carefully.

53
MCQeasy

Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?

A.'x'
B.'r+'
C.'w'
D.'a'
AnswerD

Correct: append mode.

Why this answer

Option D ('a') is correct because the 'a' mode opens a file for appending, which means new data is written to the end of the file without truncating any existing content. This is the standard behavior defined in Python's open() function for append mode.

Exam trap

Python Institute often tests the confusion between 'w' (which truncates) and 'a' (which appends), and candidates mistakenly choose 'w' thinking it simply writes without realizing it destroys existing data.

How to eliminate wrong answers

Option A ('x') is wrong because 'x' is exclusive creation mode — it opens a file for writing but fails if the file already exists, and it does not append. Option B ('r+') is wrong because 'r+' opens a file for both reading and writing, but it does not automatically position the write pointer at the end; it starts at the beginning and can overwrite existing content. Option C ('w') is wrong because 'w' opens a file for writing and truncates the file to zero length, destroying all existing content.

54
MCQhard

Refer to the exhibit. If 'data.txt' does not exist, what happens?

A.A NameError is raised because f is not defined in the finally block.
B.The function returns None.
C.A FileNotFoundError is raised and not caught.
D.The file is created and then closed.
AnswerA

f is not assigned due to the exception, so f.close() fails.

Why this answer

The open() call raises FileNotFoundError, so f is never assigned. The finally block tries to call f.close() on an undefined variable, causing a NameError.

55
MCQeasy

A developer writes a script that reads a configuration file. If the file does not exist, the program should print an error and continue. Which code snippet correctly implements this behavior?

A.try: open('config.txt') except FileNotFoundError: print('File not found')
B.f = open('config.txt', 'r') if not f: print('File not found')
C.try: f = open('config.txt') except: print('File not found')
D.try: with open('config.txt') as f: pass except Exception: print('File not found')
AnswerA

Correctly catches only FileNotFoundError.

Why this answer

Option A is correct because it uses a `try` block to attempt opening the file and catches only `FileNotFoundError`, which is the specific exception raised when the file does not exist. This allows the program to print an error and continue execution without crashing, precisely matching the requirement.

Exam trap

Python Institute often tests the distinction between catching a specific exception versus a broad or bare `except`, and the trap here is that candidates may think any `try-except` works, overlooking the requirement to catch only `FileNotFoundError` for precise error handling.

How to eliminate wrong answers

Option B is wrong because `open()` does not return a falsy value when the file is missing; it raises a `FileNotFoundError` before any assignment occurs, so the `if not f` check is never reached. Option C is wrong because it uses a bare `except:` clause, which catches all exceptions (including unrelated ones like `KeyboardInterrupt` or `PermissionError`), violating best practices and potentially masking bugs. Option D is wrong because it catches the overly broad `Exception` class, which is too general and could hide unexpected errors; the requirement specifically needs to catch only `FileNotFoundError`.

56
MCQhard

Refer to the exhibit. What does the 'from None' clause do in the second raise statement?

A.It causes the original exception to be ignored.
B.It prevents chaining of exceptions, so only the final exception is displayed.
C.It causes both exceptions to be raised simultaneously.
D.It replaces the original exception with a new one.
AnswerB

The 'from None' disables exception chaining.

Why this answer

Using 'from None' suppresses the chained exception context, so only the second exception is shown.

57
MCQhard

Which of the following exception classes is NOT a direct subclass of Exception in Python?

A.IOError
B.SystemExit
C.StopIteration
D.ValueError
AnswerB

SystemExit inherits from BaseException directly.

Why this answer

SystemExit is not a direct subclass of Exception; it inherits from BaseException instead. This is because SystemExit, along with KeyboardInterrupt and GeneratorExit, is intended to signal that the interpreter should exit, and catching it with a generic except Exception clause would be inappropriate. All other options (IOError, StopIteration, ValueError) are direct subclasses of Exception.

Exam trap

Python Institute often tests the distinction between BaseException and Exception, trapping candidates who assume all built-in exceptions inherit from Exception, when in fact SystemExit, KeyboardInterrupt, and GeneratorExit are direct subclasses of BaseException.

How to eliminate wrong answers

Option A is wrong because IOError is a direct subclass of Exception (and in Python 3, it is an alias of OSError, which also inherits from Exception). Option C is wrong because StopIteration is a direct subclass of Exception, used to signal the end of an iterator. Option D is wrong because ValueError is a direct subclass of Exception, raised when a built-in operation or function receives an argument with the right type but an inappropriate value.

58
MCQeasy

Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?

A.An unhandled exception is raised
B.'Permission denied'
C.Nothing; the program continues silently
D.'File not found'
AnswerB

Correctly caught by PermissionError.

Why this answer

When the `open()` function is called on a file that exists but the user lacks read permission, Python raises a `PermissionError` exception. The code does not include a try-except block to handle this exception, so the program terminates with an unhandled exception and prints the error message 'Permission denied' (the string representation of the exception). Option B is correct because that is the default behavior of Python when such an exception is not caught.

Exam trap

Python Institute often tests the distinction between file existence errors (FileNotFoundError) and permission errors (PermissionError), and candidates mistakenly assume that a missing file is the only possible file-related exception.

How to eliminate wrong answers

Option A is wrong because an unhandled exception is indeed raised, but the question asks what will be printed — the exception's error message ('Permission denied') is printed, not just an unhandled exception without output. Option C is wrong because Python does not silently continue when a file permission error occurs; it raises an exception that must be caught to avoid termination. Option D is wrong because the file config.cfg exists (as stated in the question), so a 'File not found' error would only occur if the file did not exist, which is not the case here.

59
Multi-Selectmedium

Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)

Select 2 answers
A.Using print(e.args)
B.Using traceback.format_exc()
C.Using sys.exc_info()
D.Using raise without argument
E.Using logging.exception() inside except block
AnswersB, E

Returns traceback string, suitable for logging.

Why this answer

Option B is correct because `traceback.format_exc()` returns the full traceback as a string, which can be logged or printed to capture detailed exception context. Option E is correct because `logging.exception()` automatically includes the traceback of the current exception when called inside an `except` block, making it the idiomatic way to log exceptions in Python.

Exam trap

Python Institute often tests the distinction between merely accessing exception data (like `e.args` or `sys.exc_info()`) and actually formatting or logging it properly, so candidates mistakenly think any function that touches exception info qualifies as a 'logging technique'.

60
MCQhard

Refer to the exhibit. A developer ran the script and saw the above traceback. The intended behavior was to load a JSON configuration file, and if the file is missing, create a default config. What is the most likely root cause of the second exception (NameError)?

A.The variable 'f' was not defined due to the FileNotFoundError.
B.The script did not import the json module.
C.The config.json file exists but is empty.
D.The file was opened in binary mode instead of text mode.
AnswerB

NameError: name 'json' is not defined indicates the import is missing.

Why this answer

Option B is correct because the traceback shows a NameError for 'json.loads', which indicates that the name 'json' is not defined in the current namespace. This occurs when the script attempts to call json.loads() without first importing the json module. The intended behavior of loading a JSON configuration file requires the json module to parse the file content, and its absence causes the NameError exception.

Exam trap

Python Institute often tests the distinction between file I/O exceptions (like FileNotFoundError) and name resolution errors (NameError), trapping candidates who focus on the file handling part of the traceback rather than recognizing that the second exception is about an undefined module name.

How to eliminate wrong answers

Option A is wrong because the NameError occurs after the FileNotFoundError is handled (the traceback shows the exception chain), and the variable 'f' is not referenced in the json.loads() call; the error is about the name 'json', not 'f'. Option C is wrong because an empty file would not cause a NameError; it would cause a json.JSONDecodeError when trying to parse empty content, not a missing name. Option D is wrong because opening a file in binary mode (e.g., 'rb') would not cause a NameError; it would affect how the file content is read (bytes vs string), but the json.loads() function can still be called if the module is imported, and the error would be a TypeError or similar, not a NameError.

61
MCQeasy

Refer to the exhibit. The above log shows an unhandled exception that caused the program to crash. The developer wants to handle this exception and log the error without crashing. Which exception type should be caught in the main code to capture this specific error?

A.BaseException
B.ValueError
C.OSError
D.Exception
AnswerB

The log explicitly shows ValueError being raised.

Why this answer

The traceback shows that a ValueError was raised. To handle this specific exception, the code should catch ValueError. Catching Exception would also work but is less specific.

Catching BaseException catches system-exit exceptions. OSError is unrelated.

62
MCQhard

A Python application processes user-uploaded files. The requirement is to catch any I/O-related exception while reading the file, but not to catch KeyboardInterrupt or SystemExit. Which exception type should be caught?

A.OSError
B.IOError
C.Exception
D.BaseException
AnswerA

Covers I/O errors while avoiding system-exiting exceptions.

Why this answer

Option A is correct because `OSError` is the base class for all I/O-related exceptions in Python 3, including file reading errors like `FileNotFoundError` and `PermissionError`. It does not catch `KeyboardInterrupt` or `SystemExit`, which inherit directly from `BaseException`, not `Exception`. This makes `OSError` the precise choice for catching I/O errors while allowing program termination signals to propagate.

Exam trap

Python Institute often tests the Python 3 exception hierarchy change where `IOError` is no longer a separate class but an alias of `OSError`, tempting candidates to pick the familiar `IOError` from Python 2 instead of the correct `OSError`.

How to eliminate wrong answers

Option B is wrong because `IOError` was merged into `OSError` in Python 3 and is now an alias; catching `IOError` would work in Python 2 but is deprecated and not the recommended modern approach. Option C is wrong because `Exception` catches all built-in exceptions that inherit from it, including `KeyboardInterrupt` and `SystemExit` (which inherit from `BaseException`), violating the requirement to not catch those. Option D is wrong because `BaseException` is the root of all exceptions and would catch everything, including `KeyboardInterrupt` and `SystemExit`, which is explicitly disallowed.

63
Multi-Selecthard

Consider the following code snippet: x = [1, 2, 3] try: print(x[5]) except IndexError: print('Index') except LookupError: print('Lookup') Which THREE statements about this code are correct? (Select exactly 3.)

Select 4 answers
A.The code will print 'Lookup' because LookupError is more general.
B.If the line with IndexError is removed, then LookupError will catch the exception.
C.IndexError is a subclass of LookupError.
D.If the code were accessing a dictionary key, LookupError would catch KeyError.
E.The output of this code is 'Index'.
AnswersB, C, D, E

Without the specific handler, the next matching handler (LookupError) will catch it.

Why this answer

Option B is correct because when the IndexError handler is removed, the exception propagates to the next matching except clause. Since IndexError is a subclass of LookupError, the LookupError handler will catch the raised IndexError. This demonstrates the hierarchical nature of exception handling in Python, where a more general exception class can catch exceptions of its subclasses.

Exam trap

Python Institute often tests the order of except clauses and the exception hierarchy, trapping candidates who assume that a more general exception handler will always catch an exception first, or who forget that Python uses first-match semantics rather than best-match.

64
Multi-Selectmedium

Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?

Select 2 answers
A.lines = list(f)
B.for line in f:
C.contents = f.read().split('\n')
D.while True: line = f.readline(); if not line: break
E.lines = f.readlines()
AnswersB, D

Iterates one line at a time.

Why this answer

Option B is correct because iterating directly over a file object with `for line in f:` reads one line at a time from the file's internal buffer, never loading the entire file into memory. This is the idiomatic and memory-efficient way to process large files line by line in Python.

Exam trap

Python Institute often tests the distinction between methods that load the entire file into memory (like `readlines()`, `read().split()`, and `list(f)`) versus the iterator protocol that processes lines lazily, and candidates frequently confuse `list(f)` as being lazy because it uses the file object.

65
Multi-Selecteasy

Which TWO of the following file modes will create a new file if it doesn't exist? (Select exactly 2)

Select 2 answers
A.'x'
B.'a'
C.'rb'
D.'w'
E.'r'
AnswersB, D

Creates new file if not exists.

Why this answer

Option B ('a') is correct because the append mode opens a file for writing at the end; if the file does not exist, Python creates it automatically. Option D ('w') is correct because write mode truncates the file if it exists, but also creates a new file if it does not exist.

Exam trap

Python Institute often tests the distinction between 'w' (truncates existing content) and 'a' (preserves existing content) while both create the file if missing, and candidates may incorrectly think 'x' or 'r' also create files.

66
MCQhard

Consider the following code snippet: try: x = int(input()) y = 10 / x print(y) except ZeroDivisionError: print('Division by zero') except ValueError: print('Invalid integer') If the user enters '0', what is the output?

A.No output
B.Both 'Invalid integer' and 'Division by zero'
C.Division by zero
D.Invalid integer
AnswerC

ZeroDivisionError is raised and caught.

Why this answer

When the user enters '0', the input is successfully converted to the integer 0 by int(), so no ValueError occurs. Then 10 / 0 raises a ZeroDivisionError, which is caught by the except ZeroDivisionError block, printing 'Division by zero'. Option C is correct because the code never reaches the ValueError handler.

Exam trap

Python Institute often tests the order of exception handling and the fact that int('0') succeeds, leading candidates to mistakenly think a ValueError occurs or that both exceptions could fire.

How to eliminate wrong answers

Option A is wrong because the ZeroDivisionError is raised and caught, so there is output ('Division by zero'), not no output. Option B is wrong because only one exception occurs (ZeroDivisionError), not both; the ValueError handler is only triggered if int() fails, which it does not here. Option D is wrong because 'Invalid integer' would only print if the input could not be converted to an integer (e.g., entering 'abc'), but '0' is a valid integer string.

67
MCQhard

A developer is implementing a custom context manager to manage database connections. The context manager should automatically roll back the transaction if an exception occurs, but commit if no exception occurs. Which pattern ensures this behavior correctly?

A.def __exit__(self, exc_type, exc_val, exc_tb): self.connection.commit()
B.def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: self.connection.rollback() else: self.connection.commit()
C.def __exit__(self, exc_type, exc_val, exc_tb): self.connection.rollback()
D.def __exit__(self, exc_type, exc_val, exc_tb): if exc_val: self.connection.rollback() else: self.connection.commit()
AnswerB

Checks exc_type; if not None, an exception occurred, so rollback; else commit.

Why this answer

Option B is correct because the `__exit__` method receives the exception type (`exc_type`), value (`exc_val`), and traceback (`exc_tb`) as arguments. By checking `if exc_type:` (which is `None` when no exception occurs, and a class object otherwise), the developer can conditionally roll back the transaction on an exception or commit if the block completes normally. This pattern ensures atomicity and proper resource management for database connections.

Exam trap

Python Institute often tests the distinction between checking `exc_type` vs. `exc_val` vs. `exc_tb`, and candidates mistakenly think any of these three can be used interchangeably, but the canonical and most reliable check is `exc_type` because it is `None` when no exception occurs and a class object otherwise, while `exc_val` could theoretically be `None` even if an exception is raised (though rare).

How to eliminate wrong answers

Option A is wrong because it always calls `commit()`, even when an exception occurs, which would commit partial or erroneous changes and violate transaction atomicity. Option C is wrong because it always calls `rollback()`, discarding successful transactions and causing data loss. Option D is wrong because it checks `exc_val` (the exception instance) instead of `exc_type`; while `exc_val` is also `None` when no exception occurs, the standard and most reliable check is `exc_type` (or `exc_val`), but the option's logic is technically correct in practice, however the question's correct answer explicitly uses `exc_type` as the canonical pattern; more importantly, the option's phrasing 'if exc_val' is less idiomatic and could be considered a trap, but the primary reason it's wrong is that the exam expects the exact pattern shown in B.

68
MCQeasy

What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')

A.no error\ndone
B.error\nno error\ndone
C.done
D.error\ndone
AnswerD

Correct: exception caught, else skipped, finally executed.

Why this answer

Option D is correct because the code raises a ZeroDivisionError when attempting 1/0, which is caught by the bare except clause, printing 'error'. The else clause is skipped because an exception occurred. The finally clause always executes, printing 'done'.

Thus the output is 'error' followed by 'done'.

Exam trap

Python Institute often tests the order of execution in try/except/else/finally, specifically that the else block is skipped when an exception occurs, and that finally always runs, leading candidates to mistakenly include 'no error' or omit 'error'.

How to eliminate wrong answers

Option A is wrong because it suggests the except block was skipped and the else block ran, which would only happen if no exception occurred; but 1/0 raises an exception. Option B is wrong because it includes 'no error' from the else block, which is never executed when an exception is caught. Option C is wrong because it omits 'error', implying the except block did not execute, but the exception is indeed caught and handled.

69
MCQeasy

Which of the following is the correct way to open a file for writing in text mode, ensuring that if the file already exists it will be overwritten?

A.open('file.txt', 'x')
B.open('file.txt', 'w')
C.open('file.txt', 'r+')
D.open('file.txt', 'a')
AnswerB

'w' mode overwrites existing content.

Why this answer

Option B is correct because the 'w' mode opens the file for writing in text mode and truncates the file to zero length if it exists, or creates a new file if it does not. This ensures any existing content is overwritten, which matches the requirement.

Exam trap

Python Institute often tests the distinction between 'w' and 'x' modes, where candidates mistakenly choose 'x' thinking it creates a new file for writing, but forget that 'x' raises an error if the file already exists, failing the overwrite requirement.

How to eliminate wrong answers

Option A is wrong because 'x' mode opens the file for exclusive creation, raising a FileExistsError if the file already exists, rather than overwriting it. Option C is wrong because 'r+' mode opens the file for both reading and writing without truncating it, so existing content is preserved and not overwritten unless explicitly written over. Option D is wrong because 'a' mode opens the file for appending, writing data at the end of the file without truncating or overwriting existing content.

70
MCQeasy

A developer needs to write binary data to a file. Which file mode should be used to open the file for writing in binary mode without truncating it if it already exists?

A.'wb'
B.'rb'
C.'ab'
D.'wb+'
AnswerC

Opens for appending in binary; does not truncate; writes at end.

Why this answer

Option C ('ab') is correct because the 'a' mode opens the file for appending, which writes data at the end without truncating the existing content, and adding 'b' specifies binary mode. This allows binary data to be written to a file that already exists without losing its current contents.

Exam trap

Python Institute often tests the distinction between 'w' (truncate) and 'a' (append) modes, trapping candidates who assume 'wb' is the only way to write binary data without considering preservation of existing content.

How to eliminate wrong answers

Option A ('wb') is wrong because 'w' mode truncates the file to zero length upon opening, destroying any existing data. Option B ('rb') is wrong because 'r' mode opens the file for reading only, not writing. Option D ('wb+') is wrong because 'w+' mode also truncates the file upon opening, even though it allows both reading and writing.

71
MCQhard

What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')

A.a b
B.b a
C.a\nb
D.b
AnswerC

Correct: prints 'a', newline, then 'b'.

Why this answer

Option C is correct because the `finally` block always executes after the `try` block, even when an exception is raised. The `except` block catches the `ValueError` and prints the first argument of the exception (`'a'`), then the `finally` block prints `'b'`. The output is `a` on one line and `b` on the next, matching `a\nb`.

Exam trap

Python Institute often tests the misconception that `finally` runs before `except` or that `print()` outputs on the same line, leading candidates to choose options with incorrect order or missing newlines.

How to eliminate wrong answers

Option A is wrong because it suggests both outputs appear on the same line (`a b`), but `print()` adds a newline by default, so they appear on separate lines. Option B is wrong because it reverses the order to `b a`, but the `finally` block executes after the `except` block, not before. Option D is wrong because it omits the `'a'` output entirely, but the `except` block does execute and prints the exception argument before the `finally` block runs.

72
Multi-Selecteasy

Which TWO of the following are built-in Python exceptions?

Select 2 answers
A.CustomException
B.InputError
C.ValueError
D.FileNotFoundError
E.FileReadError
AnswersC, D

Built-in exception for invalid value.

Why this answer

ValueError (C) is a built-in Python exception that is raised when a built-in operation or function receives an argument with the correct type but an inappropriate value, such as int('abc'). FileNotFoundError (D) is a built-in exception in Python 3, raised when a file or directory is requested but does not exist, commonly encountered during file I/O operations like open().

Exam trap

Python Institute often tests the distinction between built-in exceptions and user-defined or non-existent exceptions, and the trap here is that candidates may confuse InputError or FileReadError with real built-in exceptions like EOFError or OSError, or assume that any error related to input or files must be a built-in exception.

73
MCQmedium

A developer wants to ensure that a file is always closed, even if an exception occurs, without using the 'with' statement. Which approach correctly achieves this?

A.f = open('file.txt'); try: ... except: ... else: f.close()
B.f = open('file.txt'); try: ... finally: f.close()
C.if f.closed: pass else: f.close()
D.try: f = open('file.txt'); ... except: pass; finally: f.close()
AnswerB

Correct: finally ensures close.

Why this answer

Option B is correct because the `finally` block is guaranteed to execute regardless of whether an exception occurs in the `try` block. This ensures that `f.close()` is always called, properly releasing the file resource. The `with` statement is not used, but the `try...finally` construct provides the same deterministic cleanup behavior.

Exam trap

Python Institute often tests the distinction between `else` and `finally` in exception handling, trapping candidates who think `else` runs unconditionally or that placing `open()` inside the `try` block is safe without checking for assignment failure.

How to eliminate wrong answers

Option A is wrong because the `else` block only runs if no exception occurs; if an exception is raised, `f.close()` is never executed, leaving the file open. Option C is wrong because it references `f.closed` before `f` is defined in the given code snippet, and even if defined, it does not guarantee closure after an exception — it is a conditional check, not a cleanup mechanism. Option D is wrong because the `except` block contains `pass`, which silently swallows exceptions, and although `finally` runs, the `try` block includes the `f = open(...)` statement; if `open()` itself raises an exception (e.g., file not found), `f` is never assigned, causing a `NameError` in the `finally` block when trying to call `f.close()`.

74
MCQhard

A developer is working on a data pipeline that processes files from untrusted sources. The pipeline should catch and log any exception, but also ensure that sensitive information from the exception (e.g., file paths) is not exposed to end users. Which approach balances security and debugging?

A.Catch the exception and re-raise the same exception.
B.Catch the exception, log it, and suppress it silently.
C.Catch the exception, log the full traceback, then raise a custom generic exception.
D.Catch the exception and print it to the console.
AnswerC

Logs details for developers, raises a safe exception to users.

Why this answer

Option C is correct because it balances security and debugging: the full traceback is logged for developers (preserving debugging details like file paths), while a custom generic exception is raised to end users, preventing sensitive information from being exposed. This approach follows the principle of least privilege for error handling, ensuring that internal details are not leaked to untrusted sources.

Exam trap

Python Institute often tests the distinction between logging exceptions for debugging versus exposing them to users, and the trap here is that candidates may choose Option A (re-raise) thinking it preserves the exception chain, but they overlook the security requirement to hide sensitive details from end users.

How to eliminate wrong answers

Option A is wrong because re-raising the same exception would expose the original exception's details (including sensitive file paths) to the end user, violating security requirements. Option B is wrong because suppressing the exception silently hides all debugging information from logs, making it impossible for developers to diagnose issues in the pipeline. Option D is wrong because printing the exception to the console exposes sensitive information directly to the user or console output, which is insecure and does not log for debugging.

75
MCQmedium

A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?

A.except (FileNotFoundError, PermissionError):
B.except FileNotFoundError, PermissionError:
C.except OSError:
D.except [FileNotFoundError, PermissionError]:
AnswerA

Correct tuple syntax.

Why this answer

Option A is correct because Python's exception handling syntax allows a tuple of exception types in a single `except` clause, enabling the programmer to catch multiple exception types with the same handler. Both `FileNotFoundError` and `PermissionError` are subclasses of `OSError`, but using the tuple explicitly catches only those two specific exceptions, not all `OSError` subtypes.

Exam trap

Python Institute often tests the distinction between the correct tuple syntax `except (Exc1, Exc2):` and the incorrect comma-separated syntax `except Exc1, Exc2:` (which is a Python 2 relic), or the overly broad `except OSError:` that catches more than intended.

How to eliminate wrong answers

Option B is wrong because it uses a comma instead of parentheses, which is the old Python 2 syntax for catching exceptions and assigning the exception instance to a variable; in Python 3, this raises a `SyntaxError`. Option C is wrong because while `FileNotFoundError` and `PermissionError` are both subclasses of `OSError`, catching `OSError` would also catch many other unrelated exceptions (e.g., `FileExistsError`, `IsADirectoryError`), which is not what the programmer wants. Option D is wrong because square brackets denote a list, not a tuple; Python's `except` clause requires a tuple of exception types, and using a list will raise a `TypeError`.

Page 1 of 2 · 80 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Exceptions File Io questions.