Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- How do try, except, else and finally work together in Python?
try holds the risky code, except handles an error, else runs only if no exception occurred, and finally always runs, whether or not there was an error. Use else for code that depends on the try succeeding.
BeginnerQuick answer1 min read - How do you create and raise a custom exception in Python?
Subclass Exception (not BaseException), give it a clear name ending in Error, and raise it with raise. Add attributes or a message in __init__ if callers need details. A shared base class lets callers catch a whole family.
BeginnerQuick answer1 min read - What does the assert statement do, and when should you not use it?
assert condition, message raises AssertionError if the condition is false. It is for internal sanity checks during development. Do not use it to validate user input, because assertions are removed when Python runs with the -O flag.
BeginnerQuick answer1 min read - What is the difference between EAFP and LBYL in Python?
LBYL (look before you leap) checks conditions first, like if key in d. EAFP (easier to ask forgiveness than permission) just tries the operation and handles the exception. Python code usually prefers EAFP, especially where checking and acting could race.
IntermediateQuick answer1 min read - Why is a bare "except:" considered bad practice in Python?
A bare except catches everything, including KeyboardInterrupt and SystemExit, so Ctrl+C stops working and real bugs get hidden. Catch specific exceptions, or at most "except Exception", and log or re-raise what you cannot handle.
IntermediateQuick answer1 min read - What does this function return when both try and finally have a return statement?
It returns the value from the finally block. finally always runs last, and a return inside it overrides the earlier return and even discards a pending exception. This is why returning from finally is considered bad practice.
AdvancedQuick answer1 min read