6. Functions¶
A function is the Python version of a Scratch custom block from Unit 2 — a named, reusable chunk of code you define once and call as many times as you like.
def greet(name):
return f"Hello, {name}!"
print(greet("Alex"))
print(greet("Sam"))
Hello, Alex!
Hello, Sam!
name is a parameter — a value the function receives when it's called. return sends a value back to wherever the function was called from, so you can use the result in other code.
def take_damage(health, amount):
return health - amount
health = 3
health = take_damage(health, 1)
print(health)
2
Try it
Write a function take_damage(health, amount) like the one above, then call it a few times with different amounts and print the result each time.
Tip
A function that never hits a return line still finishes — it just hands back None instead of a value.