Card 13: Parameters

Module 5: Reusable Code

1 The Hook

A function is like a Vending Machine.

  • Input (Parameters): Money + Button Press.
  • Process: Machine checks money, finds item.
  • Output (Return): The snack drops out.

Start thinking: Input -> Function -> Output.

2 Worked Example

A machine that adds two numbers.

# Input goes in brackets (a, b)
def add_machine(a, b):
# Output comes out
return a + b
# Use it
result = add_machine(5, 10)
print(result) # Prints 15

PREDICT

What does this machine return?

def magic(x):
  return x * x

print(magic(5))

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Username Creator

1. Look at make_user. It currently just returns "FirstName".
2. Modify it to return first + last (Combine them).
3. Test it.

> _
SILVER (FIX)

🥈 Broken Calculator

This subtraction machine needs TWO numbers (inputs), but the lazy user only gave one!
1. Run it to see the error.
2. Fix the line subtract(10) by adding a second number, e.g., subtract(10, 3).

> _
GOLD (MAKE)

🥇 Area Factory

1. Define function calculate_area(w, h).
2. Return w * h.
3. Print the area of a 5x5 square.

> _