Upgrading from Wizard to Inventor
So far, you have been using spells (commands) that other people wrote:
print()input()range()
But what if you want to make your own spell?
What if you want a command called greet_player()?
Defining a Function
We use the keyword def (short for “define”).
def greet_player():
print("Welcome, brave adventurer!")
print("Prepare for glory!")
Run this. … Nothing happened?
That’s because we only defined (created) the spell. We haven’t cast (called) it yet.
Calling the Function
To use it, we just type its name:
greet_player()
Output:
Welcome, brave adventurer!
Prepare for glory!
You can call it as many times as you want!
greet_player()
greet_player()
Functions with Ingredients (Arguments)
Some spells need ingredients. print() needs text. Your function can take ingredients too!
def greet(name):
print("Hello", name)
print("Nice to meet you.")
Now we pass the name when we call it:
greet("Elena")
greet("Sam")
Output:
Hello Elena
Nice to meet you.
Hello Sam
Nice to meet you.
Why Use Functions?
- Laziness: Write code once, use it 100 times.
- Organization: Groups related code together (like a chapter in a book).
- Clarity:
check_game_over()is easier to read than 10 lines of if/else code.
Try It Yourself
Write a function called double_number(number) that takes a number and prints the double of it (number * 2).
This post is part of the Python Basics for Kids series, based on “Python for Kids from 8 to 88”.