Beginner Python interview questions
Q1 Beginner Async Generators & Async Context Managers
Short answer
An async generator is a function defined with 'async def' that uses 'yield' inside it, producing an object supporting the asynchronous iteration protocol (__anext__) instead of the regular one — it lets each item be produced after an 'await', unlike a regular generator which is…
Full answer with examples Q2 Beginner Command-Line Interfaces (argparse)
Short answer
Instantiate argparse.ArgumentParser(), call add_argument() for each expected argument, then call parse_args() to parse sys.argv and return a Namespace object with the parsed values as attributes.
Full answer with examples Q3 Beginner Comprehensions & Generators
Short answer
A list comprehension `[expr for item in iterable]` builds a new list in one concise expression, evaluating 'expr' for each item — functionally equivalent to a for loop that appends to a list, but generally more readable and slightly faster since it avoids repeated append()…
Full answer with examples Q4 Beginner Concurrency (asyncio/threading/multiprocessing)
Short answer
Concurrency means multiple tasks make PROGRESS over overlapping time periods (not necessarily simultaneously); parallelism means tasks run LITERALLY AT THE SAME INSTANT on different CPU cores.
Full answer with examples Q5 Beginner Data Types & Structures
Short answer
A list is MUTABLE (elements can be added, removed, or changed after creation), created with square brackets; a tuple is IMMUTABLE (fixed once created), created with parentheses — tuples are also slightly faster and can be used as dictionary keys or set elements, unlike lists.
Full answer with examples Q6 Beginner Dataclasses & NamedTuples
Short answer
@dataclass automatically generates __init__ (accepting each declared field as a parameter), __repr__ (a readable string representation), and __eq__ (comparing all fields for equality) based on the class's type-annotated attributes, eliminating boilerplate you'd otherwise write…
Full answer with examples Q7 Beginner Debugging & Profiling
Short answer
Insert 'import pdb; pdb.set_trace()' (or the shorter 'breakpoint()' in Python 3.7+) at the line where you want execution to pause — this drops you into an interactive debugger prompt where you can inspect variables, step through code, and evaluate expressions.
Full answer with examples Q8 Beginner Decorators
Short answer
A decorator is a function that takes another function as input and returns a (usually modified or wrapped) function as output; `@decorator_name` above a function definition is pure syntactic sugar for `func = decorator_name(func)`, applied immediately after the function is…
Full answer with examples Q9 Beginner Descriptors & Properties
Short answer
@property turns a method into a computed, READ-ONLY (by default) attribute — calling it WITHOUT parentheses runs the underlying method and returns its result, letting you expose computed values with clean attribute syntax instead of requiring an explicit method call.
Full answer with examples Q10 Beginner Exception Handling
Short answer
Code in 'try' runs normally; if it raises an exception, Python looks for the FIRST 'except' clause matching that exception's type (checked top to bottom) and runs it — if none match, the exception propagates up the call stack, potentially crashing the program if never caught…
Full answer with examples Q11 Beginner File I/O & Context Managers
Short answer
'with open(path) as f:' guarantees the file is properly closed when the block exits, EVEN IF an exception occurs inside it — manually calling open() and close() risks leaking the file handle if an exception happens between them and close() is never reached.
Full answer with examples Q12 Beginner Functions & Scope
Short answer
Positional arguments are matched to parameters by ORDER; keyword arguments are matched by explicit NAME (param=value), letting you pass arguments out of order and making the call site more self-documenting — a function call can freely mix both, positional first.
Full answer with examples Q13 Beginner functools & Functional Programming Tools
Short answer
functools provides higher-order functions that act on or return other functions, such as tools for caching (lru_cache, cache), partial application (partial), reducing sequences (reduce), and customizing comparisons (cmp_to_key, total_ordering).
Full answer with examples Q14 Beginner Iterators & the Iterator Protocol
Short answer
An iterable is any object implementing __iter__() that returns an iterator, such as lists, tuples, and dicts -- you can loop over it repeatedly.
Full answer with examples Q15 Beginner Logging
Short answer
logging supports severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), can be routed to multiple destinations (console, files, network) simultaneously, includes timestamps and context automatically, and can be toggled or filtered without editing code -- print() offers none of…
Full answer with examples Q16 Beginner Magic Methods & Operator Overloading
Short answer
Magic methods are special methods surrounded by double underscores (e.g., __init__, __str__, __add__) that Python calls implicitly in response to built-in operations like construction, printing, arithmetic, or comparisons.
Full answer with examples Q17 Beginner Memory Management & Garbage Collection
Short answer
CPython uses automatic reference counting as its primary memory management mechanism: every object tracks how many references point to it, and when that count drops to zero, the memory is immediately deallocated.
Full answer with examples Q18 Beginner Metaclasses & Class Customization
Short answer
A metaclass is 'the class of a class' -- it defines how classes themselves are constructed, just as a class defines how instances are constructed.
Full answer with examples Q19 Beginner Modules & Packaging
Short answer
A module is a single .py file containing Python definitions and statements that can be imported.
Full answer with examples Q20 Beginner Multiple Inheritance & MRO
Short answer
Multiple inheritance lets a class inherit from more than one base class simultaneously, combining attributes and methods from all of them, unlike single inheritance where a class has exactly one direct parent.
Full answer with examples Q21 Beginner Async Generators & Async Context Managers
Short answer
'async for' is the asynchronous equivalent of a regular 'for' loop — it awaits each call to the generator's __anext__() method, pausing until the next value is ready, and must itself be used inside an 'async def' function.
Full answer with examples Q22 Beginner Command-Line Interfaces (argparse)
Short answer
A positional argument is REQUIRED and identified by its ORDER on the command line (declared without a leading dash); an optional argument is identified by a FLAG name (starting with '-' or '--') and is optional by default unless you explicitly mark it 'required=True'.
Full answer with examples Q23 Beginner Comprehensions & Generators
Short answer
Add an 'if condition' clause after the 'for' clause; only items for which the condition is truthy are included in the resulting list, exactly like a for loop with a nested 'if' before the append.
Full answer with examples Q24 Beginner Concurrency (asyncio/threading/multiprocessing)
Short answer
Create a threading.Thread object, passing the target function (and optional args), then call .start() to begin execution concurrently, and .join() to wait for it to finish before continuing.
Full answer with examples Q25 Beginner Data Types & Structures
Short answer
A set stores only UNIQUE elements (duplicates are automatically discarded) and doesn't preserve insertion order in the general case; a list preserves both order AND duplicates — sets also provide much faster O(1) average membership testing (`in`) compared to a list's O(n) linear…
Full answer with examples Q26 Beginner Dataclasses & NamedTuples
Short answer
namedtuple(typename, field_names) creates a NEW tuple subclass whose elements can be accessed both by INDEX (like a regular tuple) and by NAMED ATTRIBUTE, combining a tuple's lightweight immutability with readable, self-documenting field access.
Full answer with examples Q27 Beginner Debugging & Profiling
Short answer
Use an f-string with the '=' specifier (Python 3.8+) to automatically print both the variable's NAME and its value in one concise expression, avoiding the tedium of manually typing 'print(f"variable_name: {variable_name}")'.
Full answer with examples Q28 Beginner Decorators
Short answer
Define an outer function taking the target function as its parameter, define an inner 'wrapper' function that prints, calls the original function, and returns its result, then return the wrapper — the wrapper REPLACES the original function.
Full answer with examples Q29 Beginner Descriptors & Properties
Short answer
Define a second method with the SAME name, decorated with @property_name.setter — this method runs whenever someone assigns to the property, letting you validate or transform the incoming value before storing it (typically in a differently-named private attribute).
Full answer with examples Q30 Beginner Exception Handling
Short answer
Code in 'finally' ALWAYS runs after try (and any except) completes, whether an exception occurred or not, and even if the try block contains a 'return' — making it the standard place for cleanup code like closing a file or releasing a lock.
Full answer with examples Q31 Beginner File I/O & Context Managers
Short answer
read() returns the ENTIRE file's contents as a single string; readline() returns just the NEXT single line (including its trailing newline); readlines() returns a LIST of every line in the file — read() and readlines() both load the whole file into memory at once.
Full answer with examples Q32 Beginner Functions & Scope
Short answer
A default value (`def func(param=default):`) is used when the caller omits that argument — critically, the default expression is evaluated ONCE, at FUNCTION DEFINITION time, not on every call, which matters for mutable defaults.
Full answer with examples Q33 Beginner Logging
Short answer
DEBUG (detailed diagnostic info), INFO (confirmation things work as expected), WARNING (something unexpected but not fatal), ERROR (a serious problem, functionality failed), and CRITICAL (a very serious error, program may be unable to continue).
Full answer with examples Q34 Beginner Magic Methods & Operator Overloading
Short answer
__str__ should return a readable, user-facing string (used by print() and str()), while __repr__ should return an unambiguous, ideally eval-able representation useful for debugging (used by the REPL and repr()).
Full answer with examples Q35 Beginner Modules & Packaging
Short answer
__init__.py marks a directory as a regular Python package and runs when the package is first imported, letting you control what's exposed at the package level (e.g., re-exporting submodule contents), set up package-wide state, or simply exist as an empty file to establish the…
Full answer with examples Q36 Beginner Async Generators & Async Context Managers
Short answer
An async context manager implements __aenter__ and __aexit__ (both coroutines, defined with 'async def') instead of the synchronous __enter__/__exit__ — used with 'async with' to manage a resource whose setup or teardown itself requires awaiting, like an async database…
Full answer with examples Q37 Beginner Comprehensions & Generators
Short answer
A generator function contains at least one 'yield' statement; calling it doesn't run the function body immediately — it returns a generator object, and the body only executes incrementally, one step at a time, each time you request the next value (via next() or a for loop).
Full answer with examples Q38 Beginner Concurrency (asyncio/threading/multiprocessing)
Short answer
Define your entry-point coroutine with 'async def', then call asyncio.run(coroutine()) from regular (synchronous) code — this creates a new event loop, runs the coroutine to completion, and closes the loop, serving as the standard top-level entry point for an asyncio program.
Full answer with examples Q39 Beginner Data Types & Structures
Short answer
Access a value with dict[key] (raises KeyError if missing) or dict.get(key, default) (returns None or a default instead); add/update with dict[key] = value; remove with del dict[key] or dict.pop(key), the latter also returning the removed value.
Full answer with examples Q40 Beginner Exception Handling
Short answer
List the exception types as a TUPLE after 'except', separated by commas — the clause catches ANY of the listed types, running the same handling code regardless of which specific one was raised.
Full answer with examples