🐍 Python for Everyone

← Back to practice bank

Chapter 10 Coding Challenges 55-70 min, auto-graded

Coding Challenges: Functions Deep Dive

8 HackerRank-style challenges, auto-graded right in your browser — no setup required. Write your function in the code box, then click Run Tests to check it against a set of test cases (including edge cases like n = 0 and empty inputs). Stuck? Every challenge has a Show Solution reveal at the bottom. Only uses what Chapters 1-10 have covered so far — def, default arguments, *args/**kwargs, global/nonlocal, recursion, closures, and hand-written decorators. No try/except, file I/O, classes, or imports.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name.

1 Price With Tax Easy

Write a function price_with_tax(price, tax_rate=0.08) that returns price plus tax_rate of price, rounded to 2 decimal places, using a default argument for tax_rate.

Constraints: price may be 0; tax_rate may be overridden by the caller; round the final result to 2 decimal places with round(..., 2).
Examples:
price_with_tax(100) → 108.0
price_with_tax(100, 0.1) → 110.0
price_with_tax(0) → 0.0
challenge_1.py
Show Solution
solution_1.py
def price_with_tax(price, tax_rate=0.08):
    return round(price + price * tax_rate, 2)

2 Sum Any Number of Values Easy

Write a function total_of(*args) that returns the sum of however many positional arguments are passed in, using *args.

Constraints: may be called with zero arguments (return 0); arguments may be negative.
Examples:
total_of(1, 2, 3) → 6
total_of() → 0
total_of(-1, 1) → 0
challenge_2.py
Show Solution
solution_2.py
def total_of(*args):
    return sum(args)

3 Format a Record From Keyword Arguments Easy

Write a function format_record(fields) that takes a dictionary fields and returns a single string joining every entry as "key=value" pairs separated by ", ", in insertion order. Do the actual joining inside a small nested helper that takes **kwargs, and call that helper by unpacking the dict into it with **fields — that's the **kwargs pattern this challenge is really testing, just wired up so the outside caller can hand you a single dict.

Constraints: fields may be an empty dict (return ""); values may be strings or numbers.
Examples:
format_record({"name": "Asha", "age": 21}) → "name=Asha, age=21"
format_record({}) → ""
format_record({"x": 1}) → "x=1"
challenge_3.py
Show Solution
solution_3.py
def format_record(fields):
    def _format(**kwargs):
        return ", ".join(f"{k}={v}" for k, v in kwargs.items())
    return _format(**fields)

4 Recursive Factorial Easy

Write a recursive function factorial(n) that returns n! (the product of every whole number from 1 to n), with factorial(0) equal to 1 as the base case.

Constraints: n is always a non-negative integer; must be implemented recursively (no loop-based fallback).
Examples:
factorial(0) → 1
factorial(5) → 120
factorial(10) → 3628800
challenge_4.py
Show Solution
solution_4.py
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

5 Recursive Digit Sum Medium

Write a recursive function digit_sum(n) that returns the sum of the digits of n. The base case is when n is already a single digit (less than 10) — return n directly. Otherwise, return the last digit (n % 10) plus the recursive digit sum of the rest of the number (n // 10).

Constraints: n is always a non-negative integer, including 0; must be implemented recursively.
Examples:
digit_sum(0) → 0
digit_sum(123) → 6
digit_sum(9999) → 36
challenge_5.py
Show Solution
solution_5.py
def digit_sum(n):
    if n < 10:
        return n
    return (n % 10) + digit_sum(n // 10)

6 Count Numbers in a Nested List Medium

Write a recursive function count_numbers(data) that takes a list which may contain numbers and/or other nested lists (nested arbitrarily deep), and returns a count of how many individual numbers appear in total, at every level.

Constraints: data may be empty, or contain empty nested lists (they contribute 0); nesting depth is not fixed.
Examples:
count_numbers([1, 2, [3, 4], [5, [6, 7, 8]]]) → 8
count_numbers([]) → 0
count_numbers([1, [2, [3, [4]]]]) → 4
challenge_6.py
Show Solution
solution_6.py
def count_numbers(data):
    count = 0
    for item in data:
        if isinstance(item, list):
            count += count_numbers(item)
        else:
            count += 1
    return count

7 Closure-Based Running Totals Medium

Write a function running_totals(amounts) that builds a closure-based accumulator internally: a local total = 0, plus a nested function add(amount) that uses nonlocal total to add amount to total and return the new running total. Then, using that same add closure, process every value in amounts in order and return a list of the running total after each one.

Constraints: amounts may be empty (return []); values may be negative; the running total must persist across every value in amounts via nonlocal, not be recomputed from scratch each time.
Examples:
running_totals([10, 5, -3]) → [10, 15, 12]
running_totals([]) → []
running_totals([1, 1, 1, 1]) → [1, 2, 3, 4]
challenge_7.py
Show Solution
solution_7.py
def running_totals(amounts):
    total = 0

    def add(amount):
        nonlocal total
        total += amount
        return total

    return [add(amount) for amount in amounts]

8 Call-Counting Decorator Medium

Write a function call_n_times(n) that, internally, defines a small function ping() returning "pong", and a decorator with_call_count(fn) that wraps fn so every call to the wrapped version calls the original fn (ignoring its return value) and instead returns how many times the wrapped function has been called so far, starting at 1 on the first call (track the running count with nonlocal inside the decorator). Wrap ping with with_call_count, call the wrapped version n times, and return the result of the final call (0 if n is 0, since the wrapped function is never called).

Constraints: n may be 0 (return 0); the call count must start at 1 on the first call and increase by 1 each subsequent call.
Examples:
call_n_times(3) → 3
call_n_times(1) → 1
call_n_times(0) → 0
challenge_8.py
Show Solution
solution_8.py
def call_n_times(n):
    def with_call_count(fn):
        calls = 0

        def wrapper(*args, **kwargs):
            nonlocal calls
            calls += 1
            fn(*args, **kwargs)
            return calls

        return wrapper

    def ping():
        return "pong"

    counted_ping = with_call_count(ping)
    result = 0
    for _ in range(n):
        result = counted_ping()
    return result
← Practice Bank Interview Questions →