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