Python functions interview questions
25 questions interviewers ask on functions, from first principles to the follow-ups. The first 3 model answers are free to read; Pro opens the rest.
Defining and calling
- What is the difference between a parameter and an argument?●
A parameter is the name in the function's definition,
priceindef with_tax(price):. An argument is the value passed in a call,12.50inwith_tax(12.50). At the call, the parameter is bound to the argument's object in the call's frame. - What does a function return if it has no
returnstatement?●None, if its body finishes normally. A function that prints its result instead of returning it looks right in a notebook, buttotal = show_tax(12.50)leavestotalasNone, andtotal + 1givesTypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. - How do you return several values from a function?●
Return them separated by commas; Python packs them into a tuple, and the caller unpacks it.
to_hms(7384)returns(2, 3, 4), andh, m, s = to_hms(7384)binds the three names. - What is the difference between
with_taxandwith_tax(12.50)?●● - Are type hints enforced?●●
- What is a docstring, and how do you read one?●
Arguments
- What is the difference between positional and keyword arguments?●
- What are
*argsand**kwargs?●● - What does a bare
*or a/mean in a signature?●● - What is the mutable default argument problem?●●
- Does Python pass arguments by value or by reference?●●
Scope
- What is the LEGB rule?●
- Why does
count += 1inside a function raiseUnboundLocalErrorwhencountis a global?●● - What happens to a function's local variables when it returns?●●
Recursion
- What are the two parts of a recursive function?●
- What is a
RecursionError, and what causes it?●● - When would you choose recursion over a loop?●●
- What is the call stack?●●
Functions as values
- What is a lambda, and what can it not contain?●
- How does
key=work insorted,minandmax?●● - What does it mean that Python's sort is stable, and why does it matter?●●
- What do
mapandfilterreturn? Would you use them?●● - What is a higher-order function? Give an example.●●
- What does this print, and why?
fs = [lambda: i for i in range(3)], then[f() for f in fs].●● - What does
functools.cachedo?●●