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. except
B. catch
C. handle
D. error

3 Why might a program use multiple except blocks?

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

4 Which keyword is used to raise an exception manually?

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

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

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

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

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

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

Exceptions with functions Easy
A. Inside a comment
B. Only by the operating system
C. By the calling code
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. Importing a package
B. Defining a class name
C. Starting a loop
D. Cleaning up resources

10 How is a custom exception commonly created in Python?

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

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

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

12 What is a Python module?

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

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

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

14 Which statement imports only sqrt from the math module?

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

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

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

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

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

17 What is a Python package?

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

18 Which statement best describes the Python standard library?

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

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

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

20 Which practice helps make Python code modular and maintainable?

Writing modular, maintainable, error-resilient code Easy
A. Repeating all code in one block
B. Ignoring all errors
C. Using unclear variable names
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. 12.5
B. The program terminates before printing
C. 0
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. No handler is selected
C. except ValueError
D. except TypeError

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

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

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 raises an IndexError
B. It raises a ValueError
C. It returns 0
D. It returns -2

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. No output
B. abc
C. Invalid
D. None

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. Terminate Python immediately
C. Raise a suitable exception
D. Print an error and return normally

27 When does a finally block normally execute?

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

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

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

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

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

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

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

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. format_name.helpers("sam")
C. module.helpers.format_name("sam")
D. helpers("sam").format_name

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

Finding modules Medium
A. os.environ
B. sys.argv
C. sys.path
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. The sqrt function
B. The math package only
C. Every name in math
D. A new module named sqrt

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

Executing modules as scripts Medium
A. To run it only when the file is executed directly
B. To identify syntax errors
C. To hide all functions from imports
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. reload.importlib(module)
B. import module.reload
C. module.import()
D. importlib.reload(module)

36 Which statement best describes a Python package?

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

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

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

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 formatted string
C. A datetime object
D. A date object only

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. Use focused functions and targeted handlers
C. Repeat the same validation in every line
D. Catch every error and ignore it

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. None
B. 10
C. 0
D. The program terminates before print

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. No handler executes because conversion succeeds
B. Both handlers execute in source order
C. The zero-division handler, assigning 0
D. The tuple handler, assigning -1

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 raises TypeError because comparisons are invalid
B. It returns None after printing the message
C. It raises ValueError with message out of range
D. It returns -2 because validation is advisory

44 What does caller() return?

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

def caller():
    return worker()

Exceptions with functions Hard
A. None, because finally cancels both returns
B. 4, because finally overrides the earlier return
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 stream remains open because process failed
B. The exception is suppressed after closing
C. The stream closes before the exception propagates
D. The finally block runs only for handled exceptions

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. object
C. BaseException only
D. Exception

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. An import error occurs on the second import
B. 3
C. 1
D. 2

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. The current working directory, then only built-in modules
C. Current script directory, PYTHONPATH entries, installation-dependent paths
D. Only the directory containing the Python executable

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 prints both values in import history order
B. It raises NameError because the module changed
C. It prints 10 because imports are dynamically reevaluated
D. It prints 5 because the imported name is locally bound

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 executed directly
B. It runs main() only when the file is imported
C. It prevents all definitions from executing during imports
D. It changes the module's package name at runtime

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 becomes a reference to the settings module
B. It is deleted from the importing namespace
C. It remains the previously imported object
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. include app.util
C. from . import util
D. import .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 returns False because their dates are different
B. It converts the aware value to local time implicitly
C. It compares both values as UTC automatically
D. It raises TypeError because naive and aware datetimes cannot be ordered

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

Writing modular, maintainable, error-resilient code Hard
A. Catch ValueError in the parser and raise RecordFormatError with the original cause
B. Expose the parser's internal exceptions so callers handle implementation details
C. Print every parsing error and continue with partially initialized data
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. Nothing, because KeyError requires an exact handler
B. key
C. Both lookup and key
D. lookup

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

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

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

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

58 What is returned by f()?

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

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

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. The finally exception is ignored after cleanup
C. Both exceptions are returned as a tuple
D. RuntimeError propagates, with the ValueError as its context

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:
    raise RecordError('invalid record')
B.
PYTHON
try:
    parse()
except ValueError as exc:
    return RecordError(exc)
C.
PYTHON
try:
    parse()
except ValueError as exc:
    raise RecordError('invalid record') from exc
D.
PYTHON
try:
    parse()
except Exception:
    raise ValueError('invalid record')