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 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 is the difference between __str__ and __repr__ in Python?
__str__ gives a readable description meant for users and is used by print() and str(). __repr__ gives an unambiguous description meant for developers, ideally looking like code that recreates the object. If only __repr__ exists, print falls back to it.
BeginnerQuick answer1 min read - What is the difference between type() and isinstance() in Python?
type(x) returns the exact class of x, so comparing with == ignores inheritance. isinstance(x, C) is True if x is an instance of C or of any subclass of C, so it is the usual choice for type checks.
BeginnerQuick answer1 min read