Unit 4: Modules and Exception Handling - Practice Quiz

CSR101 — Python Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which keyword is used to begin a block of code that may cause an exception?

Handling exceptions using try and except Easy
A. except
B. try
C. raise
D. finally

2 Which keyword is used to handle an exception in Python?

Handling exceptions using try and except Easy
A. error
B. handle
C. except
D. catch

3 Why might a program use multiple except blocks?

Multiple exception handlers Easy
A. To create extra variables
B. To repeat the same loop
C. To handle different exception types
D. To define many modules

4 Which keyword is used to raise an exception manually?

Raising exceptions Easy
A. error
B. except
C. throw
D. raise

5 What does the statement raise ValueError("Invalid value") do?

Raising exceptions Easy
A. Raises a ValueError
B. Repeats a function
C. Ends every program
D. Creates a module

6 What can happen when a function contains code that causes an exception?

Exceptions with functions Easy
A. The function becomes a module
B. The exception is always ignored
C. The exception can be handled by the function
D. The function must always return zero

7 If a function does not handle an exception, where can the exception be handled?

Exceptions with functions Easy
A. By the calling code
B. Only by the operating system
C. Inside a comment
D. By a variable name

8 When does a finally block normally execute?

Using finally to clean up Easy
A. Whether or not an error occurs
B. Only when an error occurs
C. Only before the try block
D. Only when no error occurs

9 What is a common use of a finally block?

Using finally to clean up Easy
A. Starting a loop
B. Defining a class name
C. Cleaning up resources
D. Importing a package

10 How is a custom exception commonly created in Python?

Custom exception types Easy
A. By importing finally
B. By subclassing Exception
C. By calling print()
D. By changing a comment

11 Which class is commonly used as the base class for a user-defined exception?

Custom exception types Easy
A. Exception
B. String
C. Module
D. Object

12 What is a Python module?

Modules Easy
A. A database table
B. A special keyboard
C. A file containing Python code
D. A type of loop

13 Which function can show the locations searched when Python imports modules?

Finding modules Easy
A. module.list()
B. os.find()
C. sys.path
D. import.path()

14 Which statement imports only sqrt from the math module?

Importing specific names from a module Easy
A. import sqrt from math
B. include math.sqrt
C. from math import sqrt
D. using math.sqrt

15 What does if __name__ == "__main__": help identify?

Executing modules as scripts Easy
A. Code inside a loop
B. A custom data type
C. Code run as a script
D. A missing variable

16 Why might a module be reloaded during an interactive Python session?

Reloading modules Easy
A. To convert code to HTML
B. To use recent code changes
C. To delete all Python files
D. To create a new interpreter

17 What is a Python package?

Packages and standard library Easy
A. A collection of related modules
B. A command-line prompt
C. A single number
D. A type of exception

18 Which statement best describes the Python standard library?

Packages and standard library Easy
A. Built-in collection of useful modules
B. A list of user passwords
C. A tool for drawing only
D. A separate programming language

19 Which module provides classes for working with dates and times?

datetime Easy
A. calendar_time
B. date_tools
C. time_data
D. datetime

20 Which practice helps make Python code modular and maintainable?

Writing modular, maintainable, error-resilient code Easy
A. Using unclear variable names
B. Repeating all code in one block
C. Ignoring all errors
D. Using small focused functions

21 What is printed by this code?

PYTHON
try:
    value = int("12.5")
except ValueError:
    value = 0
print(value)

Handling exceptions using try and except Medium
A. 0
B. 12.5
C. The program terminates before printing
D. None

22 Which handler is selected when data = [10, 20] and the statement print(data[2]) is executed?

Multiple exception handlers Medium
A. except IndexError
B. except TypeError
C. No handler is selected
D. except ValueError

23 What is the main reason specific exception handlers should usually appear before a general except Exception handler?

Multiple exception handlers Medium
A. Specific handlers prevent syntax errors
B. Specific handlers execute more quickly
C. The general handler could intercept errors first
D. General handlers cannot catch built-in errors

24 What happens when this function is called with age = -2?

PYTHON
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

Raising exceptions Medium
A. It returns -2
B. It returns 0
C. It raises a ValueError
D. It raises an IndexError

25 What is printed by this code?

PYTHON
def convert(text):
    return int(text)

try:
    print(convert("abc"))
except ValueError:
    print("Invalid")

Exceptions with functions Medium
A. Invalid
B. No output
C. None
D. abc

26 Which design best allows a function to report invalid input while letting its caller decide how to respond?

Exceptions with functions Medium
A. Return a random fallback value
B. Print an error and return normally
C. Raise a suitable exception
D. Terminate Python immediately

27 When does a finally block normally execute?

Using finally to clean up Medium
A. Only when no exception occurs
B. Only when the function returns
C. After the try or except processing
D. Only when an exception occurs

28 Which action is most appropriate for a finally block after manually opening a file?

Using finally to clean up Medium
A. Delete the file contents
B. Close the file
C. Read the file again
D. Raise a new exception

29 Which definition correctly creates a custom exception for an invalid account balance?

Custom exception types Medium
A. class BalanceError(Error): pass
B. class BalanceError: raise Exception
C. def BalanceError(Exception): pass
D. class BalanceError(Exception): pass

30 Why might a program use a custom InsufficientFundsError instead of raising a generic Exception?

Custom exception types Medium
A. It automatically records transactions
B. It prevents all other exceptions
C. It removes the need for testing
D. It identifies a specific failure condition

31 Suppose helpers.py contains def format_name(name): return name.title(). Which statement calls that function after importing the module?

Modules Medium
A. helpers.format_name("sam")
B. helpers("sam").format_name
C. format_name.helpers("sam")
D. module.helpers.format_name("sam")

32 Which feature helps determine the locations Python searches when importing modules?

Finding modules Medium
A. sys.path
B. sys.argv
C. os.environ
D. builtins.path

33 What does from math import sqrt make available directly in the current namespace?

Importing specific names from a module Medium
A. Every name in math
B. The math package only
C. The sqrt function
D. A new module named sqrt

34 Why is code commonly placed under if __name__ == "__main__":?

Executing modules as scripts Medium
A. To identify syntax errors
B. To hide all functions from imports
C. To run it only when the file is executed directly
D. To force a module to reload

35 After changing a module during an interactive session, which action reloads it using importlib?

Reloading modules Medium
A. importlib.reload(module)
B. import module.reload
C. reload.importlib(module)
D. module.import()

36 Which statement best describes a Python package?

Packages and standard library Medium
A. A folder that groups related modules
B. A compiled exception handler
C. A single variable with many values
D. A temporary interpreter command

37 Which module belongs to Python's standard library and can be imported without installing an external package?

Packages and standard library Medium
A. numpy
B. pandas
C. requests
D. datetime

38 Which expression creates a datetime object representing the current local date and time?

datetime Medium
A. datetime.date.today()
B. datetime.datetime.now()
C. datetime.time.current()
D. datetime.datetime.date()

39 What does this expression produce?

PYTHON
from datetime import datetime
moment = datetime.strptime("2025-03-08", "%Y-%m-%d")

datetime Medium
A. A Unix timestamp
B. A date object only
C. A formatted string
D. A datetime object

40 Which approach best supports maintainable and error-resilient Python code?

Writing modular, maintainable, error-resilient code Medium
A. Put all logic in one large function
B. Repeat the same validation in every line
C. Catch every error and ignore it
D. Use focused functions and targeted handlers

41 What is printed by this code?

PYTHON
try:
    result = 10 / 0
except ZeroDivisionError:
    result = 0
print(result)

Handling exceptions using try and except Hard
A. 10
B. The program terminates before print
C. None
D. 0

42 Which handler is selected when value is the string "7"?

PYTHON
try:
    number = int(value)
    answer = 100 / number
except (TypeError, ValueError):
    answer = -1
except ZeroDivisionError:
    answer = 0

Multiple exception handlers Hard
A. The zero-division handler, assigning 0
B. The tuple handler, assigning -1
C. No handler executes because conversion succeeds
D. Both handlers execute in source order

43 What is the effect of this function when called with -2?

PYTHON
def percentage(value):
    if not 0 <= value <= 100:
        raise ValueError('out of range')
    return value

Raising exceptions Hard
A. It returns None after printing the message
B. It returns -2 because validation is advisory
C. It raises ValueError with message out of range
D. It raises TypeError because comparisons are invalid

44 What does caller() return?

PYTHON
def worker():
    try:
        return 3
    finally:
        return 4

def caller():
    return worker()

Exceptions with functions Hard
A. 4, because finally overrides the earlier return
B. None, because finally cancels both returns
C. A RuntimeError, because two returns are illegal
D. 3, because the try return occurs first

45 Which statement best describes this code if process(stream) raises an exception?

PYTHON
stream = open('data.txt')
try:
    process(stream)
finally:
    stream.close()

Using finally to clean up Hard
A. The exception is suppressed after closing
B. The finally block runs only for handled exceptions
C. The stream remains open because process failed
D. The stream closes before the exception propagates

46 Which definition best supports catching a domain-specific error while preserving normal exception behavior?

PYTHON
class InvalidRecordError(_____):
    pass

Custom exception types Hard
A. ValueError and TypeError simultaneously
B. Exception
C. BaseException only
D. object

47 Suppose tools.py contains count = 1, and the following code runs:

PYTHON
import tools
import tools
tools.count += 1
print(tools.count)



What is printed?

Modules Hard
A. 3
B. An import error occurs on the second import
C. 2
D. 1

48 Which lookup order most accurately describes how Python searches for a top-level imported module?

Finding modules Hard
A. The package cache, then the operating system registry
B. Current script directory, PYTHONPATH entries, installation-dependent paths
C. Only the directory containing the Python executable
D. The current working directory, then only built-in modules

49 If config.py defines timeout = 5, what happens here?

PYTHON
from config import timeout
# config.py is later changed so timeout = 10
print(timeout)

Importing specific names from a module Hard
A. It raises NameError because the module changed
B. It prints 5 because the imported name is locally bound
C. It prints 10 because imports are dynamically reevaluated
D. It prints both values in import history order

50 What is the purpose of this guard?

PYTHON
if __name__ == '__main__':
    main()

Executing modules as scripts Hard
A. It runs main() only when the file is imported
B. It changes the module's package name at runtime
C. It prevents all definitions from executing during imports
D. It runs main() only when the file is executed directly

51 Assume from settings import limit has already executed and settings.limit is then changed to 20. After importlib.reload(settings), what is true about limit?

Reloading modules Hard
A. It remains the previously imported object
B. It becomes a reference to the settings module
C. It is deleted from the importing namespace
D. It automatically becomes 20

52 A package contains app/util.py and app/main.py. Which import is generally appropriate inside app/main.py when app is imported as a package?

Packages and standard library Hard
A. from package app import util
B. from . import util
C. import .util
D. include app.util

53 What is the key issue with this comparison?

PYTHON
from datetime import datetime, timezone
naive = datetime.now()
aware = datetime.now(timezone.utc)
print(naive < aware)

datetime Hard
A. It converts the aware value to local time implicitly
B. It raises TypeError because naive and aware datetimes cannot be ordered
C. It returns False because their dates are different
D. It compares both values as UTC automatically

54 Which design best prevents a low-level parsing detail from leaking into application code?

Writing modular, maintainable, error-resilient code Hard
A. Print every parsing error and continue with partially initialized data
B. Expose the parser's internal exceptions so callers handle implementation details
C. Catch ValueError in the parser and raise RecordFormatError with the original cause
D. Catch every exception in the parser and return an empty record

55 What is printed?

PYTHON
try:
    raise KeyError('x')
except LookupError:
    print('lookup')
except KeyError:
    print('key')

Handling exceptions using try and except Hard
A. lookup
B. key
C. Nothing, because KeyError requires an exact handler
D. Both lookup and key

56 Which handler structure correctly distinguishes a missing key from an invalid integer while avoiding unreachable-handler problems?

Multiple exception handlers Hard
A. except LookupError followed by except KeyError
B. except KeyError followed by except ValueError
C. except Exception followed by except KeyError
D. except (KeyError, Exception) followed by except ValueError

57 What does a bare raise do inside an active except block?

Raising exceptions Hard
A. Raises a new generic Exception without context
B. Reraises the currently handled exception with its traceback
C. Suppresses the exception and exits the function
D. Raises the last exception created anywhere in the process

58 What is returned by f()?

PYTHON
def f():
    try:
        1 / 0
    except ZeroDivisionError:
        return 'handled'
    return 'after'

Exceptions with functions Hard
A. handled
B. The ZeroDivisionError propagates
C. None
D. after

59 Which outcome occurs here?

PYTHON
try:
    raise ValueError('bad')
finally:
    raise RuntimeError('cleanup failed')

Using finally to clean up Hard
A. ValueError propagates because it was raised first
B. Both exceptions are returned as a tuple
C. RuntimeError propagates, with the ValueError as its context
D. The finally exception is ignored after cleanup

60 Which pattern correctly preserves the original failure while translating it to an application-level exception?

Custom exception types Hard
A.
PYTHON
try:
    parse()
except ValueError as exc:
    return RecordError(exc)
B.
PYTHON
try:
    parse()
except ValueError as exc:
    raise RecordError('invalid record') from exc
C.
PYTHON
try:
    parse()
except ValueError:
    raise RecordError('invalid record')
D.
PYTHON
try:
    parse()
except Exception:
    raise ValueError('invalid record')