Lesson 8 of 30
Lesson 08 — Functions are magic buttons
Title: Reuse code with def
Description: Create functions that greet people, make animal sounds, calculate points, and return answers.
Why it matters for kids: A function lets you teach Python a new command.
1. First function
def say_hello():
print("Hello!")
print("Welcome to Python.")
say_hello()
say_hello()The function does nothing until you call it.
2. Function with a parameter
def greet(name):
print(f"Hello, {name}!")
greet("Mia")
greet("Leo")
greet("Sam")A parameter is information the function needs.
3. Animal sounds
def make_animal_sound(animal, sound):
print(f"The {animal} says {sound}!")
make_animal_sound("cat", "meow")
make_animal_sound("dog", "woof")
make_animal_sound("duck", "quack")4. Return an answer
def add_points(first_score, second_score):
return first_score + second_score
total = add_points(10, 15)
print("Total points:", total)return sends a value back.
5. Easy examples
def build_robot_name(color):
return f"{color} Bot"
print(build_robot_name("Red"))
print(build_robot_name("Blue"))def is_winning(score):
return score >= 100
print(is_winning(50))
print(is_winning(120))def print_stars(count):
print("*" * count)
print_stars(3)
print_stars(8)6. Mini challenge
Click each example to open it.
Example 1
Create a function that prints hello.
Example 2
Call the hello function twice.
Example 3
Create a function with one name parameter.
Example 4
Create a function that prints an animal sound.
Example 5
Create a function that adds two numbers.
Example 6
Return a robot name from a function.
Example 7
Return double of a number.
Example 8
Make a function that prints stars.
Example 9
Make a function that checks a high score.
Example 10
Make describe_pet with name and animal.