Elena' s AI Blog

Creating Spells: Writing Your Own Functions

05 Jan 2026 / 2 minutes to read

Elena Daehnhardt


Lesson 9 of 10 90%


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

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?

  1. Laziness: Write code once, use it 100 times.
  2. Organization: Groups related code together (like a chapter in a book).
  3. 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”.

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