PYTHON PROGRAMMING · 15 MIN READ

Writing useful Python functions

A function gives a repeatable task a name, inputs, and—when needed—a result.

Learning objectives

  • Define and call a function.
  • Distinguish printing a value from returning it.

Define a contract

PYTHON
def area(width, height):
    return width * height

room_area = area(4, 3)

width and height are parameters. The call supplies arguments 4 and 3. return sends the computed value to the caller, so room_area becomes 12.

Common mistakes

  • A function without an explicit return returns None.
  • Keep a function focused; a name such as area should not also print menus or read files.
  • Test edge cases such as zero or negative values when the domain forbids them.

Applications and references

Functions make calculations, parsing, validation, and formatting independently understandable and testable.