Elena' s AI Blog

Creating Spells: Writing Your Own Functions

05 Jan 2026 / 12 minutes to read

Elena Daehnhardt


Lesson 9 of 11 81%


TL;DR: A function is a block of code with a name. `def my_spell():` creates it. `my_spell()` runs it. It makes code reusable.

Upgrading from Wizard to Inventor ๐Ÿ”ง

Functions are like creating your own spells

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) ๐Ÿฅ„

Functions take inputs and produce outputs

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โ€.

desktop bg dark

About Elena

Elena, a PhD in Computer Science, simplifies AI concepts and helps you use machine learning.

Citation
Elena Daehnhardt. (2026) 'Creating Spells: Writing Your Own Functions', daehnhardt.com, 05 January 2026. Available at: https://daehnhardt.com/courses/book0/09-functions/
Course Library