Related chapter: Functions and Modules

Exercise 1: Calculator Functions

Write four functions: add, subtract, multiply, divide. divide should raise ValueError on division by zero.

  divide(10, 3)   # 3.333...
divide(10, 0)   # ValueError
  

Exercise 2: Default Arguments

Write create_profile(name, age, city="Unknown", active=True) that returns a dict. Test with varying arguments.

Exercise 3: *args Sum

Write flexible_sum(*args) that returns the sum of any number of numeric arguments.

  flexible_sum(1, 2, 3)       # 6
flexible_sum(10)             # 10
flexible_sum(1, 2, 3, 4, 5) # 15
  

Exercise 4: Word Frequency

Write word_frequency(text) that returns a dict of word counts (case-insensitive, ignore punctuation).

  word_frequency("Hello hello world!")
# {'hello': 2, 'world': 1}
  

Exercise 5: Recursive Fibonacci

Write fib(n) using recursion with memoization (functools.lru_cache).

  fib(10)  # 55
fib(50)  # 12586269025 (instant with lru_cache)
  

Exercise 6: Function as Argument

Write apply_twice(func, value) that applies a function twice.

  apply_twice(lambda x: x + 1, 5)   # 7
apply_twice(lambda x: x * 2, 3)   # 12
  

Challenge: Decorator from Scratch

Write a @timer decorator that prints how long a function takes to run. Apply it to a slow function and verify the output.

Hint

See Decorators if you need help after trying.

Solution (Exercise 4)
  import string

def word_frequency(text):
    table = str.maketrans("", "", string.punctuation)
    clean = text.lower().translate(table)
    counts = {}
    for word in clean.split():
        counts[word] = counts.get(word, 0) + 1
    return counts
  

Exercise 7: Closure Counter

Write make_counter(start=0) that returns a function. Each call increments and returns the count.

  counter = make_counter(10)
counter()  # 11
counter()  # 12
  

Exercise 8: Pipeline

Write pipeline(value, *functions) that passes value through each function left to right.

  pipeline(5, lambda x: x + 1, lambda x: x * 2, lambda x: x ** 2)
# ((5 + 1) * 2) ** 2 = 144
  

Next: OOP Exercises