Python Functions & scope: 14 practice problems
UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise Functions & scope nowAll topicsTheory: Functions & scope in Python
THEORY
------
* DEFINE / CALL
def area(length, width=1): # parameters (width has a DEFAULT value)
"""Docstring: what it does."""
return length * width # return sends a value back and ENDS the function
area(5, 2) area(5) area(width=2, length=5) # positional / default / keyword ARGUMENTS
No return statement (or bare `return`) -> the function returns None.
Return several values -> really a tuple: return lo, hi -> lo, hi = f()
* PARAMETER KINDS (in this order): def f(a, b=2, *args, c, d=4, **kwargs)
*args extra positional args collected into a TUPLE
**kwargs extra keyword args collected into a DICT
after *args, parameters are keyword-only
Unpacking when calling: f(*my_list), f(**my_dict)
* SCOPE — the LEGB rule for looking up a name:
Local (inside the current function) -> Enclosing (outer function) -> Global (module)
-> Built-in (print, len ...)
Assigning to a name inside a function creates a LOCAL variable, even if a global exists.
count = 0
def bump():
global count # without this line: UnboundLocalError
count += 1
`nonlocal x` — rebind a variable of the ENCLOSING function (used in closures).
Mutating a global list/dict (append, d[k] = v) does NOT need `global` — you're not rebinding.
* MUTABLE DEFAULT ARGUMENT TRAP
def add(item, bag=[]): # the [] is created ONCE, when def runs -> shared between calls!
Fix: def add(item, bag=None): if bag is None: bag = []
* FUNCTIONS ARE OBJECTS: store them in variables, lists, dicts; pass them as arguments
(higher-order functions: map, filter, sorted(key=...)); return them (closures).
lambda x: x * 2 anonymous single-expression function
list(map(str.upper, words)) list(filter(lambda n: n > 0, nums))
* CLOSURE: an inner function that remembers variables of the outer function after it returns.
* RECURSION: a function calling itself; needs a BASE CASE. factorial(n) = n * factorial(n - 1)
* Good functions: do ONE thing, clear name (verb), no hidden global side effects, docstring.
14 Functions & scope practice problems
1. Calculator with a Default Operator
Easy2 ways to solve📤 OUTPUT: return an int or a float (or None in the special case), e.g. 9. Use `return`, not print().
op is one of + - * / ; default "+". Division by zero or unknown op -> None.
calculate(6, 3) -> 9 calculate(6, 3, "/") -> 2.0 calculate(1, 0, "/") -> None
Ways: if/elif · dict of lambdas {"+": lambda a, b: a + b, ...}
Solve “Calculator with a Default Operator” in your browser →2. Average of Any Number of Values — *args
Easy2 ways to solve📤 OUTPUT: return a float, e.g. 2.0. Use `return`, not print().
average(1, 2, 3) -> 2.0 average() -> 0.0
Solve “Average of Any Number of Values — *args” in your browser →3. User Profile Builder — **kwargs
Easy2 ways to solve📤 OUTPUT: return a dict with "name" first, then every keyword detail. Use `return`, not print().
Return a dict with "name" first, then every keyword detail.
build_profile("Asha", city="Pune", age=21) -> {"name": "Asha", "city": "Pune", "age": 21}
Solve “User Profile Builder — **kwargs” in your browser →4. Ticket Number Dispenser — closure + nonlocal
Medium2 ways to solve📤 OUTPUT: return a FUNCTION; each call returns the next number, starting at start + 1. Use `return`, not print().
Real world: A token machine at a bank gives 1, 2, 3, ...
Return a FUNCTION; each call returns the next number, starting at start + 1.
next_ticket = make_counter()
next_ticket() -> 1; next_ticket() -> 2
other = make_counter(100); other() -> 101 (independent counters!)
Solve “Ticket Number Dispenser — closure + nonlocal” in your browser →5. Apply a Pricing Rule — passing functions as arguments
Easy3 ways to solve📤 OUTPUT: return a NEW list of prices, e.g. [90.0, 180.0]. Use `return`, not print().
rule is a function taking a price and returning a new price. Return the new list.
apply_to_all([100, 200], lambda p: p * 0.9) -> [90.0, 180.0]
Ways: loop · list comprehension · list(map(rule, prices))
Solve “Apply a Pricing Rule — passing functions as arguments” in your browser →6. Function Composition — returning functions
Medium2 ways to solve📤 OUTPUT: return a new function h such that h(x) == f(g(x)). Use `return`, not print().
Return a new function h such that h(x) == f(g(x)).
add1 = lambda x: x + 1; double = lambda x: x * 2
compose(add1, double)(5) -> 11
Solve “Function Composition — returning functions” in your browser →7. Global Order ID — `global`
Easy1 way to solve📤 OUTPUT: return the new id as an int, e.g. 1 then 2. Use `return`, not print().
Real world: Every new order gets the next ID. Increase the GLOBAL NEXT_ID by 1 and return it.
(with NEXT_ID == 0) next_order_id() -> 1; next_order_id() -> 2
Viva: what error do you get without the global statement, and why?
Solve “Global Order ID — `global`” in your browser →8. Shopping Cart — fix the mutable default trap
Easy1 way to solve📤 OUTPUT: return the cart list, e.g. ['pen']. Use `return`, not print().
Add item to cart and return the cart. When no cart is given, start a NEW empty cart EVERY time.
add_to_cart("pen") -> ["pen"]; add_to_cart("ink") -> ["ink"] (NOT ["pen", "ink"]!)
Solve “Shopping Cart — fix the mutable default trap” in your browser →9. Factorial — recursion (base case + recursive case)
Easy3 ways to solve📤 OUTPUT: return an int, e.g. 120. Use `return`, not print().
factorial(5) -> 120 factorial(0) -> 1
Then try the loop version. Viva: what happens with factorial(5000) recursively?
Solve “Factorial — recursion (base case + recursive case)” in your browser →10. Flatten ANY Depth — recursion
Medium2 ways to solve📤 OUTPUT: return a list, e.g. [1, 2, 3, 4, 5]. Use `return`, not print().
flatten_deep([1, [2, [3, [4]], 5]]) -> [1, 2, 3, 4, 5]
Hint: isinstance(item, list) -> recurse, else append.
Solve “Flatten ANY Depth — recursion” in your browser →11. Predict the Output — scope. Return a list of what each snippet returns:
Medium1 way to solve📤 OUTPUT: return a list: [[f_result, x_after], g_result, second_h_result, v_after]. Use `return`, not print().
1) x = 10 2) x = 10
def f(): def g():
x = 5 return x * 2
return x g() -> ?
f(), then x -> [?, ?] (give both, so this item is a list of 2)
3) def h(a, lst=[]): 4) def k(n):
lst.append(a) n += 1
return len(lst) return n
h(1); h(2) -> value of 2nd call v = 3; k(v); v -> ?
Return: [[f_result, x_after], g_result, second_h_result, v_after]
Solve “Predict the Output — scope. Return a list of what each snippet returns:” in your browser →12. Retry with Exponential Backoff — interview at a payments-API company
Project1 way to solve📤 OUTPUT: return (result, delays) where delays is the list of delays used. Use `return`, not print(). Interviewer: "Bank APIs fail randomly. Retry them, waiting longer each time, but don't hammer them." Call func() up to `attempts` times. After a failure (exception), call sleep(base_delay * 2 ** i) for i = 0, 1, 2 ... BEFORE the next try (never after the last failure). Return (result, delays) where delays is the list of delays used. If every attempt fails, re-raise the LAST exception. (sleep is passed in, so tests don't really wait: a function as a parameter!)Solve “Retry with Exponential Backoff — interview at a payments-API company” in your browser →
13. Stage 11a — the Built-in Function Table
Compiler1 way to solve📤 OUTPUT: return a dict name -> (arity, function) for: abs (1), max (2), min (2), round (2: value,…. Use `return`, not print(). Return a dict name -> (arity, function) for: abs (1), max (2), min (2), round (2: value, digits), pow (2)Solve “Stage 11a — the Built-in Function Table” in your browser →
14. Stage 11b — Calling a Built-in safely
Compiler1 way to solve📤 OUTPUT: return whatever the built-in returns, e.g. 5; RAISE NameError / TypeError as described. Use `return`, not print().
builtins: a table like make_builtins(). args: list of values.
Unknown name -> raise NameError(f"unknown function {name}")
Wrong number of args -> raise TypeError(f"{name}() takes {arity} arguments ({len(args)} given)")
Otherwise return function(*args).
Solve “Stage 11b — Calling a Built-in safely” in your browser →← TUPLES (immutability) & SETS (unique elements) Modules & external packages →