Package repeated logic into functions that are easy to test and reuse.

Functions and readable code

Learning objectives

  • Define and call a function.
  • Pass arguments and return a result.
  • Separate calculation from display.
  • Test a function with more than one input.

Example

def meters_to_centimeters(meters):
    """Convert a distance in meters to centimeters."""
    return meters * 100


distance_m = 2.5
distance_cm = meters_to_centimeters(distance_m)
print(f"{distance_m} m = {distance_cm} cm")

meters is a parameter. The return statement sends a value back to the caller. A function should usually do one clear job.

Test several inputs

test_values = [0, 1, 2.5, 10]

for value in test_values:
    result = meters_to_centimeters(value)
    print(value, result)

Guided practice

Write is_safe_distance(distance_cm) that returns True when the distance is at least 20 cm. Test it with 10, 20, and 35.

def is_safe_distance(distance_cm):
    return distance_cm >= 20

Common mistakes

  • Forgetting to call the function with parentheses.
  • Printing inside a function when the caller needs the result.
  • Using a variable that only exists inside another function.
  • Giving a function several unrelated responsibilities.

Checkpoint

Explain the difference between a parameter and an argument. Add a docstring and two tests to one of your functions.

Mini-project

Refactor the robot decision simulator from the previous lesson into functions for checking one reading and summarizing a list of readings.