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.
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.
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.
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.
def make_total():
total = 10
return total
print(make_total())
print(total)