🐍 Python for Everyone

← Back to exercises

Chapter 10 Practice Bank 75-95 min, hands-on

Practice Bank: Functions Deep Dive

A deeper set of practice problems, organized by topic, for extra reps beyond the main exercises — including scenario-based problems written in the same style you'll meet in real interviews. Uses everything from Chapters 1-9 plus this chapter's own toolkit: def, parameters and default arguments, *args and **kwargs, local/global scope with global/nonlocal, recursion, closures, and decorators (hand-written, no functools). No try/except, file I/O, classes, or imports.

How to run these Download starter.py below, then run it from a terminal with python3 starter.py.

Topic 1: Function Basics

1 Your first function

Find # TODO 1.1. Write greet(name), a function that returns a greeting string.

2 Two parameters

Find # TODO 1.2. Write add(a, b), a function that returns the sum of two arguments.

3 Returning a boolean

Find # TODO 1.3. Write is_even(n), a function that returns True or False.

4 Branching inside a function

Find # TODO 1.4. Write describe_number(n) using if/elif/else inside the function body.

5 Debug the Code

Find # TODO 1.5. This function prints its result instead of returning it, so the caller gets back None. Fix it.

💼 Scenario

Order total calculator

Find # TODO 1.A. Write calculate_total(price, quantity) for a checkout flow.

💼 Interview Prep

Returning vs. printing

Find # TODO 1.B. Compare a function that returns a value against one that only prints it, and explain in a comment why the second one gives back None when you try to store its result.

Topic 2: Default Arguments

1 A default exponent

Find # TODO 2.1. Write power(base, exponent=2) with a default exponent.

2 A default greeting

Find # TODO 2.2. Write make_greeting(name, greeting="Hello") with a default greeting.

3 A default discount percent

Find # TODO 2.3. Write apply_discount(price, percent=10) with a default discount.

4 Multiple defaults

Find # TODO 2.4. Write build_profile(name, age=18, city="Unknown") and call it three different ways.

5 Debug the Code

Find # TODO 2.5. This function uses a mutable list as a default argument, so the same list is reused and grows across calls. Fix it.

💼 Scenario

Configurable report header

Find # TODO 2.A. Write report_header(title, author="Unknown Author", year=2024).

💼 Interview Prep

The mutable default trap

Find # TODO 2.B. Build a visit tracker the safe way, and explain in a comment why mutable default arguments are dangerous in Python.

Topic 3: *args and **kwargs

1 Summing any number of arguments

Find # TODO 3.1. Write sum_all(*args) to sum any number of positional arguments.

2 Joining any number of words

Find # TODO 3.2. Write join_words(*args) to join any number of words with spaces.

3 Printing keyword arguments

Find # TODO 3.3. Write print_profile(**kwargs) to print each keyword argument on its own line.

4 Collecting both together

Find # TODO 3.4. Write build_settings(*args, **kwargs), returning both collected together as a tuple.

5 Debug the Code

Find # TODO 3.5. This function tries to divide the args tuple directly instead of summing it first, raising a TypeError. Fix it.

💼 Scenario

Flexible logger

Find # TODO 3.A. Write log_event(event_name, **details), a logger that accepts any extra named details.

💼 Interview Prep

*args vs. **kwargs

Find # TODO 3.B. Write describe_call(*args, **kwargs), and explain in a comment the difference between *args and **kwargs.

Topic 4: Scope (local/global, global/nonlocal)

1 A local variable shadowing a global

Find # TODO 4.1. Show a local variable shadowing a global one of the same name without modifying the global.

2 Using global to modify a variable

Find # TODO 4.2. Use the global keyword to modify a module-level variable from inside a function.

3 Using nonlocal in a nested function

Find # TODO 4.3. Use nonlocal inside a nested function to modify an enclosing function's variable.

4 A parameter is just a local variable

Find # TODO 4.4. Show that a function parameter shadowing a global name never touches the global.

5 Debug the Code

Find # TODO 4.5. This function is missing a global declaration, raising an UnboundLocalError. Fix it.

💼 Scenario

Shared application counter

Find # TODO 4.A. Track active_users across login/logout functions using global.

💼 Interview Prep

global vs. nonlocal

Find # TODO 4.B. Build a nested counter with nonlocal, and explain in a comment the difference between global and nonlocal.

Topic 5: Recursion

1 Recursive factorial

Find # TODO 5.1. Write a recursive factorial(n).

2 Recursive fibonacci

Find # TODO 5.2. Write a recursive fibonacci(n).

3 Recursive digit sum

Find # TODO 5.3. Write a recursive sum_digits(n).

4 Recursive countdown

Find # TODO 5.4. Write a recursive count_down(n) that prints "Liftoff!" at its base case.

5 Debug the Code

Find # TODO 5.5. This recursive factorial function is missing its base case entirely, causing infinite recursion. Fix it.

💼 Scenario

Counting items in nested categories

Find # TODO 5.A. Recursively total the numbers inside a nested list of category counts.

💼 Interview Prep

Why every recursive function needs a base case

Find # TODO 5.B. Write a recursive power_of(base, exponent), and explain in a comment what a base case is and why it's required.

Topic 6: Closures

1 A closure that multiplies

Find # TODO 6.1. Write make_multiplier(factor) returning a closure that multiplies by factor.

2 Independent greetings

Find # TODO 6.2. Write make_greeter(greeting), and show two closures remembering different greetings.

3 Independent counters

Find # TODO 6.3. Write make_counter(), and show two independent counters tracking separate state.

4 A running total closure

Find # TODO 6.4. Write make_running_total() and call the returned closure repeatedly.

5 Debug the Code

Find # TODO 6.5. This closure reassigns a brand-new local list on every call instead of appending to the enclosing one, so it never accumulates. Fix it.

💼 Scenario

Per-user rate limiter counter

Find # TODO 6.A. Build a closure-based request counter that blocks requests once a limit is exceeded.

💼 Interview Prep

What is a closure?

Find # TODO 6.B. Write make_adder(n), and explain in a comment what a closure is.

Topic 7: Decorators

1 A shouting decorator

Find # TODO 7.1. Write a decorator shout that uppercases a function's string result.

2 A call-counting decorator

Find # TODO 7.2. Write a decorator call_counter that tracks how many times a function has been called.

3 A result-modifying decorator

Find # TODO 7.3. Write a decorator double_result that doubles a function's numeric result.

4 A logging decorator

Find # TODO 7.4. Write a decorator log_call that prints the arguments before calling the function.

5 Debug the Code

Find # TODO 7.5. This decorator's wrapper forgets to return the inner function's result, so every decorated call silently gives back None. Fix it.

💼 Scenario

Timing-style instrumentation without a timer

Find # TODO 7.A. Build track_calls, a decorator that logs a running call count for any function.

💼 Interview Prep

What does a decorator do under the hood?

Find # TODO 7.B. Write a decorator ensure_positive, and explain in a comment what a decorator does under the hood.

Topic 8: Bringing It Together — Real-World Functions in Production

1 A validation helper

Find # TODO 8.1. Write validate_and_format_price(price), a small validation helper for a checkout flow.

2 A defensive list-lookup pattern

Find # TODO 8.2. Write retry_with_default(values, index, default=None), safely reading from a list that might be shorter than expected.

3 A flexible API response wrapper

Find # TODO 8.3. Write build_api_response(status, **data), modeling a real API response shape.

4 A retry-once decorator

Find # TODO 8.4. Write a decorator retry_once that retries a function call once if it returns None.

5 Debug the Code

Find # TODO 8.5. This recursive discount function never decrements its rounds argument, causing infinite recursion. Fix it.

💼 Scenario

Production-style input sanitizer pipeline

Find # TODO 8.A. Write sanitize_signup_data(name, email, age=None, **extra), combining required params, a default, and **kwargs.

💼 Interview Prep

Combining a closure with a decorator

Find # TODO 8.B. Build a closure-based running-average tracker, wrap it with a logging decorator, and explain in a comment how the two compose.

Checking your work Compare your output against solution.py. Your exact wording doesn't need to match — the goal is that your program runs without errors and does what each TODO asks.
← Exercises Challenges →