21. Functions — Homework solutions

The .py solution files are in exercises/21/homework/solutions/.

Problem 1 — Greet

Problem. A function greet(name) that prints a greeting, called three times.

How to think about it. One parameter, one print line; the caller passes a string each call.

Worked solution.

def greet(name):
    print(f"Hello, {name}!")

greet("Keiko")
greet("Python")
greet("World")

Common mistakes.

  • Putting a return statement in instead of print. The function should print directly; the caller does not need a value back.
  • Forgetting the colon at the end of def greet(name):. Python requires it and raises a SyntaxError without it.

Problem 2 — is_even

Problem. Return True or False from n % 2 == 0. No printing inside the function.

How to think about it. n % 2 == 0 is already a boolean. return it directly; let the caller print it.

Worked solution.

def is_even(n):
    return n % 2 == 0

print(is_even(4))   # True
print(is_even(7))   # False
print(is_even(0))   # True
print(is_even(-2))  # True

That one line is the whole body: Python evaluates n % 2, then ... == 0, and returns the boolean.

Common mistakes.

  • Writing the function as:

    if n % 2 == 0:
        return True
    else:
        return False

    Four lines for what the one above does. n % 2 == 0 is already a boolean.

Problem 3 — Clamp

Problem. clamp(x, lo, hi) returns x bounded by lo and hi.

How to think about it. Two guard checks at the top handle the out-of-range cases; otherwise return x unchanged.

Worked solution.

def clamp(x, lo, hi):
    if x < lo:
        return lo
    if x > hi:
        return hi
    return x

print(clamp(5, 0, 10))    # 5
print(clamp(-3, 0, 10))   # 0
print(clamp(99, 0, 10))   # 10

The two if blocks are independent because each returns: the first to fire exits the function. Otherwise return x runs.

Common mistakes.

  • Expecting clamp(99, 0, 10) to be 99. Bounded by forces the output inside the range, returning 10.

Challenge — Swap

Problem. A function that returns two values swapped, plus a multi-assignment call.

How to think about it. The body is one line: return b, a. The caller writes x, y = swap(x, y) to receive both at once.

Worked solution.

def swap(a, b):
    return b, a

x = 1
y = 2

print(f"Before: x={x} y={y}")
x, y = swap(x, y)
print(f"After:  x={x} y={y}")

Output:

Before: x=1 y=2
After:  x=2 y=1

Same a, b = b, a trick from Chapter 11, wrapped in a function. It adds no power, but it gives the operation a name that makes calling code clearer.

Common mistakes.

  • Writing x, y = swap(x, y), 0. That is a syntax error or gives unexpected results. To unpack a multi-value return, the call must stand alone on the right-hand side of the assignment.

Done?

The next two chapters cover lists and dictionaries, Python's built-in data structures. Then modules for splitting code across files, and the Part 5 mini-project: a text adventure.