Functions — Exercises
Build functions, use defaults, *args/**kwargs, and return values.
1. Basics
- Write a function
is_even(n)that returns True ifnis even. - Write
greet(name, greeting='Hello')wheregreetinghas a default value.
2. Arguments
- Write
sum_all(*nums)that returns sum of arbitrary number of arguments. - Write
describe_person(name, **info)that prints provided keyword info in "key: value" format.
3. Higher-order & recursion
- Write a function
apply_twice(fn, x)that appliesfntwice tox. - Write a recursive function to compute factorial of n.
4. Exercises (integration)
- Write a function that takes a list of strings and returns a single string (comma-separated) using a helper function for formatting each item.
- Write unit-test-like checks (simple asserts) for at least two functions above.
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