Unit 4: Modules and Exception Handling - Practice Quiz
1 Which keyword is used to begin a block of code that may cause an exception?
2 Which keyword is used to handle an exception in Python?
3
Why might a program use multiple except blocks?
4 Which keyword is used to raise an exception manually?
5
What does the statement raise ValueError("Invalid value") do?
ValueError
6 What can happen when a function contains code that causes an exception?
7 If a function does not handle an exception, where can the exception be handled?
8
When does a finally block normally execute?
try block
9
What is a common use of a finally block?
10 How is a custom exception commonly created in Python?
finally
Exception
print()
11 Which class is commonly used as the base class for a user-defined exception?
12 What is a Python module?
13 Which function can show the locations searched when Python imports modules?
module.list()
os.find()
sys.path
import.path()
14
Which statement imports only sqrt from the math module?
import sqrt from math
include math.sqrt
from math import sqrt
using math.sqrt
15
What does if __name__ == "__main__": help identify?
16 Why might a module be reloaded during an interactive Python session?
17 What is a Python package?
18 Which statement best describes the Python standard library?
19 Which module provides classes for working with dates and times?
calendar_time
date_tools
time_data
datetime
20 Which practice helps make Python code modular and maintainable?
21
What is printed by this code?
try:
value = int("12.5")
except ValueError:
value = 0
print(value)
22
Which handler is selected when data = [10, 20] and the statement print(data[2]) is executed?
except IndexError
except TypeError
except ValueError
23
What is the main reason specific exception handlers should usually appear before a general except Exception handler?
24
What happens when this function is called with age = -2?
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
-2
0
ValueError
IndexError
25
What is printed by this code?
def convert(text):
return int(text)
try:
print(convert("abc"))
except ValueError:
print("Invalid")
Invalid
None
abc
26 Which design best allows a function to report invalid input while letting its caller decide how to respond?
27
When does a finally block normally execute?
28
Which action is most appropriate for a finally block after manually opening a file?
29 Which definition correctly creates a custom exception for an invalid account balance?
30
Why might a program use a custom InsufficientFundsError instead of raising a generic Exception?
31
Suppose helpers.py contains def format_name(name): return name.title(). Which statement calls that function after importing the module?
helpers.format_name("sam")
helpers("sam").format_name
format_name.helpers("sam")
module.helpers.format_name("sam")
32 Which feature helps determine the locations Python searches when importing modules?
sys.path
sys.argv
os.environ
builtins.path
33
What does from math import sqrt make available directly in the current namespace?
math
math package only
sqrt function
sqrt
34
Why is code commonly placed under if __name__ == "__main__":?
35
After changing a module during an interactive session, which action reloads it using importlib?
importlib.reload(module)
import module.reload
reload.importlib(module)
module.import()
36 Which statement best describes a Python package?
37 Which module belongs to Python's standard library and can be imported without installing an external package?
numpy
pandas
requests
datetime
38
Which expression creates a datetime object representing the current local date and time?
datetime.date.today()
datetime.datetime.now()
datetime.time.current()
datetime.datetime.date()
39
What does this expression produce?
from datetime import datetime
moment = datetime.strptime("2025-03-08", "%Y-%m-%d")
date object only
datetime object
40 Which approach best supports maintainable and error-resilient Python code?
41
What is printed by this code?
try:
result = 10 / 0
except ZeroDivisionError:
result = 0
print(result)
10
print
None
0
42
Which handler is selected when value is the string "7"?
try:
number = int(value)
answer = 100 / number
except (TypeError, ValueError):
answer = -1
except ZeroDivisionError:
answer = 0
0
-1
43
What is the effect of this function when called with -2?
def percentage(value):
if not 0 <= value <= 100:
raise ValueError('out of range')
return value
None after printing the message
-2 because validation is advisory
ValueError with message out of range
TypeError because comparisons are invalid
44
What does caller() return?
def worker():
try:
return 3
finally:
return 4
def caller():
return worker()
4, because finally overrides the earlier return
None, because finally cancels both returns
RuntimeError, because two returns are illegal
3, because the try return occurs first
45
Which statement best describes this code if process(stream) raises an exception?
stream = open('data.txt')
try:
process(stream)
finally:
stream.close()
finally block runs only for handled exceptions
process failed
46
Which definition best supports catching a domain-specific error while preserving normal exception behavior?
class InvalidRecordError(_____):
pass
ValueError and TypeError simultaneously
Exception
BaseException only
object
47
Suppose tools.py contains count = 1, and the following code runs:
import tools
import tools
tools.count += 1
print(tools.count)
What is printed?
3
2
1
48 Which lookup order most accurately describes how Python searches for a top-level imported module?
PYTHONPATH entries, installation-dependent paths
49
If config.py defines timeout = 5, what happens here?
from config import timeout
# config.py is later changed so timeout = 10
print(timeout)
NameError because the module changed
5 because the imported name is locally bound
10 because imports are dynamically reevaluated
50
What is the purpose of this guard?
if __name__ == '__main__':
main()
main() only when the file is imported
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?
settings module
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?
from package app import util
from . import util
import .util
include app.util
53
What is the key issue with this comparison?
from datetime import datetime, timezone
naive = datetime.now()
aware = datetime.now(timezone.utc)
print(naive < aware)
TypeError because naive and aware datetimes cannot be ordered
False because their dates are different
54 Which design best prevents a low-level parsing detail from leaking into application code?
ValueError in the parser and raise RecordFormatError with the original cause
55
What is printed?
try:
raise KeyError('x')
except LookupError:
print('lookup')
except KeyError:
print('key')
lookup
key
KeyError requires an exact handler
lookup and key
56 Which handler structure correctly distinguishes a missing key from an invalid integer while avoiding unreachable-handler problems?
except LookupError followed by except KeyError
except KeyError followed by except ValueError
except Exception followed by except KeyError
except (KeyError, Exception) followed by except ValueError
57
What does a bare raise do inside an active except block?
Exception without context
58
What is returned by f()?
def f():
try:
1 / 0
except ZeroDivisionError:
return 'handled'
return 'after'
handled
ZeroDivisionError propagates
None
after
59
Which outcome occurs here?
try:
raise ValueError('bad')
finally:
raise RuntimeError('cleanup failed')
ValueError propagates because it was raised first
RuntimeError propagates, with the ValueError as its context
finally exception is ignored after cleanup
60 Which pattern correctly preserves the original failure while translating it to an application-level exception?
try:
parse()
except ValueError as exc:
return RecordError(exc)try:
parse()
except ValueError as exc:
raise RecordError('invalid record') from exctry:
parse()
except ValueError:
raise RecordError('invalid record')try:
parse()
except Exception:
raise ValueError('invalid record')Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →