Sample questions
Question 1Easy
What is the output?
try:
import not_a_real_module_xyz
except ImportError as e:
print(type(e).__name__)
- FileNotFoundError
- NameError
- ModuleNotFoundError
- ImportError
Answer: C. ModuleNotFoundError
Explanation
Importing a missing module raises ModuleNotFoundError, a subclass of ImportError, so the handler catches it and prints the specific class name.
Step-by-step solution
- The module not_a_real_module_xyz does not exist.
- Python raises ModuleNotFoundError for a missing module.
- ModuleNotFoundError is a subclass of ImportError, so the except clause catches it.
- The output is ModuleNotFoundError, which is option C.
Why the other options are wrong
- A. FileNotFoundError is for missing files, not modules.
- B. The missing module raises an import error, not a NameError.
- D. The exact class printed is ModuleNotFoundError, not the broader ImportError.
Tip: Use the exact class name with type(e).__name__; ModuleNotFoundError is a kind of ImportError.
Question 2Easy
What happens when this code runs?
d = {}
print(d["k"])
- A KeyError is raised
- An IndexError is raised
- It prints None
- It prints an empty string
Answer: A. A KeyError is raised
Explanation
Indexing a dict with a missing key raises KeyError. Use d.get('k') to get None instead.
Step-by-step solution
- d is an empty dict.
- d['k'] looks up a missing key.
- Square-bracket access on a missing key raises KeyError.
Why the other options are wrong
- B. IndexError is for sequences like lists.
- C. Only d.get('k') would give None.
- D. Nothing prints an empty string.
Tip: Use d.get(k) or 'k in d' to avoid KeyError.
Question 3Easy
What is the output?
try:
n = 5 / 0
except ZeroDivisionError:
n = -1
print(n)
- ZeroDivisionError
- inf
- 0
- -1
Answer: D. -1
Explanation
Dividing by zero raises ZeroDivisionError, which is caught, and n is set to -1 in the handler.
Step-by-step solution
- 5 / 0 raises ZeroDivisionError.
- The except ZeroDivisionError branch runs and sets n = -1.
- print(n) shows -1, which is option D.
Why the other options are wrong
- A. The error is caught, so it is not printed.
- B. Python does not return inf for division by zero; it raises an error.
- C. The handler sets n to -1, not 0.
Tip: Division by zero in Python raises ZeroDivisionError; it does not give inf.
Question 4Easy
Which exception does int("abc") raise?
- SyntaxError
- ValueError
- TypeError
- NameError
Answer: B. ValueError
Explanation
The argument has the right type (str) but a value that cannot be parsed as an integer, so Python raises ValueError.
Step-by-step solution
- int() is given a string, which is the right type.
- The text abc cannot be read as a whole number, so the value is wrong.
- That raises ValueError, the correct answer.
Why the other options are wrong
- A. SyntaxError is wrong; the code is valid, and the error happens while it runs.
- C. TypeError is wrong; the type is right, only the value is bad.
- D. NameError is wrong; int is a known built-in name.
Tip: TypeError means the wrong type was given. ValueError means the right type with a bad value.
Question 5Medium
What is the output?
def f():
try:
return 1
finally:
print("F", end=" ")
print(f())
- 1
- F 1
- 1 F
- F
Answer: B. F 1
Explanation
The finally block runs before the function actually returns, so 'F ' is printed first, then print shows the returned value 1.
Step-by-step solution
- The function reaches return 1, so it will return 1, but the finally block runs first.
- Finally prints F with a space after it, and then the function returns 1.
- print(f()) then shows the returned 1 after F, giving F 1, the correct answer.
Why the other options are wrong
- A. 1 is wrong; the finally block still prints F before the function ends.
- C. 1 F is wrong; F is printed before print shows the returned value.
- D. F is wrong; the outer print also shows the returned 1.
Tip: Finally runs even after a return, and the returned value is still sent back to the caller.
Question 6Medium
What is the output?
try:
try:
1 / 0
except ZeroDivisionError as e:
raise ValueError("bad") from e
except ValueError as v:
print(type(v.__cause__).__name__)
- None
- NoneType
- ZeroDivisionError
- ValueError
Answer: C. ZeroDivisionError
Explanation
raise ... from e sets the new exception's __cause__ to e, which here is the ZeroDivisionError.
Step-by-step solution
- The ZeroDivisionError is raised by
1 / 0 and caught as e. raise ValueError from e sets the new exception's __cause__ to e.- So
v.__cause__ is the ZeroDivisionError object. - Its type name is ZeroDivisionError.
Why the other options are wrong
- A. The cause is set by
raise ... from, so it is not None. - B. The cause is an exception, not NoneType.
- D. The cause is the original ZeroDivisionError, not the ValueError.
Tip: raise NewError from err stores the original error in __cause__.
Question 7Medium
What is the output?
class AppError(Exception):
pass
class DbError(AppError):
pass
try:
raise DbError("x")
except AppError:
print("app")
except DbError:
print("db")
- db
- app
- DbError traceback
- app db
Answer: B. app
Explanation
except clauses are tested in order and DbError is a subclass of AppError, so the first clause matches; the more specific clause never runs.
Step-by-step solution
- DbError is raised and is a subclass of AppError.
- Except clauses are tried in order, so the AppError clause is checked first.
- That clause matches the subclass, so app is printed.
- The output is app.
Why the other options are wrong
- A. The first matching clause wins, and AppError is checked first.
- C. The exception is caught by a handler, so no traceback is printed.
- D. Only one clause runs, so app db is never printed.
Tip: Put more specific except clauses before more general ones.
Question 8Medium
What is the output?
def f():
try:
return "try"
finally:
return "finally"
print(f())
- finally
- SyntaxError
- try finally
- try
Answer: A. finally
Explanation
A return in finally overrides the pending return from try, so the function returns "finally". (Python 3.12 still allows it; linters warn about it.)
Step-by-step solution
- The try block returns try, but the finally block runs before the function exits.
- The finally block returns finally, which replaces the pending return value.
- So the function returns finally.
- The output is finally.
Why the other options are wrong
- B. The code is valid Python, so no SyntaxError is raised.
- C. Only one value is returned, so try finally is not produced.
- D. The return in finally overrides the return in try, so try is not printed.
Tip: A return inside finally overrides any return from try; avoid it because it hides exceptions.
Question 9Hard
What is the output?
try:
try:
raise KeyError("k")
finally:
print("F", end=" ")
except KeyError as e:
print(repr(e))
- F KeyError: k
- F 'k'
- F KeyError('k')
- KeyError('k')
Answer: C. F KeyError('k')
Explanation
finally runs while the exception propagates, printing F; the outer handler then prints repr(e), which is KeyError('k').
Step-by-step solution
- The inner finally block runs while the KeyError is propagating, so F is printed first.
- The outer except catches the KeyError as e.
- repr(e) gives KeyError('k').
- The output is F KeyError('k').
Why the other options are wrong
- A. The printed text uses repr, not the message format, so KeyError: k is not shown.
- B. Repr of a KeyError shows KeyError('k'), not just 'k'.
- D. F is printed first, because finally runs before the outer handler.
Tip: A finally block runs even when an exception passes through it; repr shows the exception type and arguments.
Question 10Hard
What is the output?
import sys
try:
sys.exit(3)
except Exception:
print("caught Exception")
except BaseException as e:
print("base", type(e).__name__, e.code)
- base SystemExit 3
- base SystemExit None
- caught Exception
- Nothing is printed; the program exits with code 3
Answer: A. base SystemExit 3
Explanation
sys.exit raises SystemExit, which inherits from BaseException but not Exception, so only the second handler catches it; code holds 3.
Step-by-step solution
- sys.exit(3) raises SystemExit, which is not a subclass of Exception.
- The first except Exception does not match it.
- The second except BaseException matches it, and the code value is 3.
- The output is base SystemExit 3.
Why the other options are wrong
- B. sys.exit(3) stores 3 in code, so the value is not None.
- C. SystemExit does not inherit from Exception, so that clause does not run.
- D. The BaseException clause catches the exit, so the program does not just exit.
Tip: SystemExit inherits from BaseException, so a plain except Exception does not catch it.
Practise all 38 questions free
The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.
Open this topic in the app →