Chapter 6

Functions: Build Programs in Pieces

Functions break a growing script into small, reusable units, each with clear inputs and outputs.

Chapter 6, Functions: Build Programs in Pieces

What you will learn

  • Define and call functions.
  • Distinguish parameters from arguments.
  • Understand return versus print.
  • Use local variables and avoid unnecessary global state.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

6.1 A Function Does Nothing Until You Call It

TPRM Lab 6.1: Your First Function

Type this into a file, predict the output, then run it.

Python
def say_hello():
    print("Hello!")

say_hello()
say_hello()

6.2 Parameters and Arguments

TPRM Lab 6.2: Pass Information In

Type this into a file, predict the output, then run it.

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

greet("Alex")
greet("Sam")

6.3 return Is Not print

TPRM Lab 6.3: Return a Result

Type this into a file, predict the output, then run it.

Python
def rectangle_area(length, width):
    area = length * width
    return area

result = rectangle_area(7, 3)
print(result)
print(result * 2)

6.4 Local Scope

Type this into a file, predict the output, then run it.

Python
def make_total():
    total = 10
    return total

print(make_total())
print(total)

Back to Python the TPRM Way