Upgrading from Wizard to Inventor ๐ง

So far, you have been using spells (commands) that other people wrote:
print()input()range()len()
But what if you want to make your own spell?
What if you want a command called greet_player() or calculate_score()?
You Can! Functions Let You Invent New Commands! โก
Before: After:
โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ print() โ โ print() โ
โ input() โ โ input() โ
โ len() โ + โ len() โ
โโโโโโโโโโโโ โ greet() โโ YOUR spell!
โ add_score() โโ YOUR spell!
โโโโโโโโโโโโโโโโ
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 called (used) it yet!
Calling the Function ๐ฏ
To use it, we just type its name with ():
greet_player()
Output:
Welcome, brave adventurer!
Prepare for glory!
You can call it as many times as you want!
greet_player()
greet_player()
greet_player()
This will print the message 3 times! Itโs like pressing a button that does a whole sequence of actions!
๐ Try This NOW!
What will this code do?
def say_hello():
print("Hello!")
print("How are you?")
say_hello()
say_hello()
Click to check!
It will print: ``` Hello! How are you? Hello! How are you? ``` The function runs twice!๐ฎ Real-World Connection
Every button in a game is a function! When you click โJumpโ in Fortnite, it calls a function jump() that makes your character jump. When you click โLikeโ on Instagram, it calls a function like_post(). Functions are how programmers organize their code!
Functions with Ingredients (Parameters) ๐ฅ

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")
greet("Alex")
Output:
Hello Elena
Nice to meet you.
Hello Sam
Nice to meet you.
Hello Alex
Nice to meet you.
Multiple Parameters
You can have MORE than one ingredient!
def introduce(name, age):
print("Hi, I'm", name)
print("I am", age, "years old")
introduce("Sam", 10)
introduce("Alex", 12)
Functions That Give Back Answers (Return) ๐
So far our functions just print things. But what if we want them to calculate something and give us the answer?
def double_number(number):
return number * 2
result = double_number(5)
print(result) # 10
The return keyword sends the answer back!
Visual Flow:
โโโโโโโโโโโโโโโโโโโโโโโ
โ double_number(5) โ
โ โ โ
โ 5 * 2 = 10 โ
โ โ โ
โ return 10 โ
โ โ โ
โ result = 10 โ
โโโโโโโโโโโโโโโโโโโโโโโ
Return vs. Print
Print shows something on screen. Return gives a value back that you can save or use.
def add(a, b):
return a + b
def greet():
print("Hello!")
# Return example:
total = add(5, 3) # total = 8 (we can save it!)
print(total * 2) # 16
# Print example:
greeting = greet() # greeting = None (nothing to save!)
Why Use Functions? ๐ค
1. Laziness (The Good Kind!)
Write code once, use it 100 times.
def calculate_score(points, bonus):
return points * 10 + bonus
level1_score = calculate_score(5, 100)
level2_score = calculate_score(8, 200)
level3_score = calculate_score(12, 500)
2. Organization
Groups related code together (like chapters in a book).
def start_game():
print("Game starting...")
def play_level():
print("Playing...")
def end_game():
print("Game over!")
start_game()
play_level()
end_game()
3. Clarity
check_game_over() is easier to read than 10 lines of if/else code!
Try It Yourself
Challenge 1: Write a function called say_goodbye() that prints โGoodbye!โ and โSee you later!โ.
Solution:
def say_goodbye():
print("Goodbye!")
print("See you later!")
say_goodbye()
Challenge 2: Write a function called square_number(num) that takes a number and returns the number multiplied by itself.
Solution:
def square_number(num):
return num * num
print(square_number(5)) # 25
print(square_number(10)) # 100
Challenge 3: Write a function called make_greeting(name, time) that creates personalized greetings!
Solution:
def make_greeting(name, time):
print("Good", time + ",", name + "!")
print("Hope you're having a great day!")
make_greeting("Elena", "morning")
make_greeting("Sam", "evening")
Extra Challenge: The Calculator
Create a calculator with 4 functions: add, subtract, multiply, divide.
Solution:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Calculator Ready!")
num1 = int(input("First number: "))
num2 = int(input("Second number: "))
op = input("Operation (+, -, *, /): ")
if op == "+":
print("Result:", add(num1, num2))
elif op == "-":
print("Result:", subtract(num1, num2))
elif op == "*":
print("Result:", multiply(num1, num2))
elif op == "/":
print("Result:", divide(num1, num2))
Common Mistakes & Fixes
โ Wrong: def greet()
print("Hi")
Why it fails: Missing the : at the end!
โ
Right: def greet():
print("Hi")
Functions need colons!
โ Wrong: def greet(name):
print(name)
Why it fails: Not indented!
โ
Right: def greet(name):
print(name)
Indent the function body!
โ Wrong: def add(x, y)
result = x + y
# Forgot to return!
โ
Right: def add(x, y):
result = x + y
return result
Use return to give back values!
โ Wrong: greet # Missing ()
Why it fails: Without (), it doesn't run!
โ
Right: greet()
Call with parentheses!
๐ Bug Hunter Betty Says:
โIf you define a function but nothing happens, make sure you CALLED it! Defining is like writing a recipeโyou also have to cook it! And if you get โNameErrorโ, make sure you defined the function BEFORE you try to use it.โ
๐ Achievement Unlocked: Spell Creator! Wizard Level: MASTER (9/10 complete - one more to go!)
๐ Todayโs Spell Book (Quick Reference)
# Define a function (creating the recipe):
def function_name():
# Code goes here
print("This runs when called")
# Call a function (using it):
function_name()
# Function with parameters (ingredients):
def greet(name):
print("Hello", name)
greet("Sam") # Pass the ingredient
# Function with return (giving back a value):
def add(x, y):
return x + y
result = add(5, 3) # result = 8
# Multiple parameters:
def introduce(name, age, hobby):
print(name, "is", age, "and likes", hobby)
introduce("Sam", 10, "gaming")
# Remember:
# - def to define
# - () to call
# - parameters = ingredients
# - return = give back value
# - indent the function body!
๐ก Parent/Teacher Tip
Functions are one of the most important concepts in programming! If your learner struggles, use cooking analogies: A recipe (function definition) tells you HOW to make cookies, but you still have to actually MAKE them (function call). Ingredients = parameters, and the finished cookies = return value.
๐ Fun Fact
Professional programmers spend more time organizing code into functions than writing new code! They follow the โDRYโ principle: Donโt Repeat Yourself. If youโre copy-pasting code, you probably need a function!
In the FINAL lesson, weโll celebrate everything youโve learned and show you whatโs next!
This post is part of the Python Basics for Kids series, based on โPython for Kids from 8 to 88โ.