Functions — Exercises

Build functions, use defaults, *args/**kwargs, and return values.

1. Basics

  1. Write a function is_even(n) that returns True if n is even.
  2. Write greet(name, greeting='Hello') where greeting has a default value.

2. Arguments

  1. Write sum_all(*nums) that returns sum of arbitrary number of arguments.
  2. Write describe_person(name, **info) that prints provided keyword info in "key: value" format.

3. Higher-order & recursion

  1. Write a function apply_twice(fn, x) that applies fn twice to x.
  2. Write a recursive function to compute factorial of n.

4. Exercises (integration)

  1. Write a function that takes a list of strings and returns a single string (comma-separated) using a helper function for formatting each item.
  2. Write unit-test-like checks (simple asserts) for at least two functions above.

← Back to Topics


Show answers — Functions worksheet

1. Basics

# 1. is_even
def is_even(n):
    return n % 2 == 0

# 2. greet with default
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"

2. Arguments

# 3. sum_all
def sum_all(*nums):
    return sum(nums)

# 4. describe_person
def describe_person(name, **info):
    print(name)
    for k, v in info.items():
        print(f"{k}: {v}")

3. Higher-order & recursion

# 5. apply_twice
def apply_twice(fn, x):
    return fn(fn(x))

# 6. factorial recursive
def fact(n):
    if n <= 1:
        return 1
    return n * fact(n-1)

4. Integration exercises

# 7. join strings
def join_commas(lst):
    return ", ".join(lst)

# 8. simple tests using assert
assert is_even(2) == True
assert sum_all(1,2,3) == 6