Quick answerThese six Python function exercises have you write functions that return values: the largest of three numbers, a leap-year test, a clamp with a default argument, a word counter, factorial with recursion and a fast Fibonacci. The checker calls each function with several arguments and compares the return values.
return vs print
A function that prints shows something on screen but gives back None. A function that returns hands a value back to the code that called it, which can store it, test it or print it. In these exercises the tests call your function โ for example is_leap(2024) โ and check what it returns, so use return.
Exercises
1. Largest of threeeasy
Write largest(a, b, c) that returns the biggest of three numbers โ without using the built-in max.
๐ก Start with best = a, then replace it if b or c is bigger.
Show solution
def largest(a, b, c):
best = a
if b > best:
best = b
if c > best:
best = c
return best
Keeping a running "best so far" is the same idea max() uses internally, and it scales to any number of values.
2. Leap yeareasy
Write is_leap(year) that returns True for leap years: divisible by 4, except centuries, which must be divisible by 400.
๐ก return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Show solution
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
A boolean expression is already True or False, so it can be returned directly โ no if/else needed.
3. Clamp with defaultsmedium
Write clamp(x, low=0, high=100) that returns x limited to the range lowโฆhigh.
๐ก Give the parameters default values in the def line, then return max(low, min(x, high)).
Show solution
def clamp(x, low=0, high=100):
return max(low, min(x, high))
Default arguments are used when the caller leaves them out, and can still be overridden by position or by name.
4. Word countermedium
Write count_words(text) that returns a dictionary mapping each lower-case word to how many times it appears.
๐ก Loop over text.lower().split() and use counts[w] = counts.get(w, 0) + 1.
Show solution
def count_words(text):
counts = {}
for w in text.lower().split():
counts[w] = counts.get(w, 0) + 1
return counts
dict.get(key, 0) returns 0 for a word we haven't seen yet, avoiding a KeyError. collections.Counter does this in one line.
5. Factorial (recursion)medium
Write a recursive factorial(n): 0! = 1 and n! = n ร (nโ1)!.
๐ก Base case: if n == 0: return 1. Otherwise return n * factorial(n - 1).
Show solution
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Every recursive function needs a base case that stops it. Watch the calls stack up in the visualizer.
6. Fast Fibonaccihard
Write fib(n) returning the n-th Fibonacci number (fib(0) = 0, fib(1) = 1). It must be fast enough for fib(200).
๐ก The starter recomputes the same values exponentially many times. Loop instead, keeping the last two numbers: a, b = b, a + b.
Show solution
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
The loop does n additions; the naive recursion does about 1.6โฟ calls โ fib(200) would never finish. Python's ints grow as big as needed.
Next topic: Dictionary exercises โ
Python Coding - Learn Python for Android: a real Python 3 interpreter, code editor, 26 example programs and 12 marked exercises.
Frequently asked questions
What is the difference between return and print in a Python function?
print shows a value on screen; return sends it back to the caller. A function without return returns None.
What are default arguments?
Parameters with a value in the def line, like def clamp(x, low=0). Callers can leave them out. Never use a mutable default like [].
When should I use recursion?
When a problem is naturally made of smaller copies of itself โ trees, nested lists, divide-and-conquer. For simple counting, a loop is usually clearer and faster.