blog.dopana

Back

Welcome to the final post of our Python for Kids series! 🚀

So far, we have taught our robot how to speak, remember details, and make decisions. But what if we want the robot to perform a complex routine—like jumping up, clapping its hands, and shouting “Hooray!”—every time we win?

Typing those lines of code again and again is tedious. Today, we will learn how to bundle code into a custom button called a Function!

What is a Function? (The Recipe Analogy)#

Think of a function as a recipe in a cookbook or a custom action button on a video game controller.

  1. Defining the Recipe (def): You write down the steps of the recipe once.
  2. Calling the Function: Whenever you want to cook it, you just yell the recipe name!
graph TD
    Call["Call: celebrate()"] --> Recipe["Recipe: def celebrate():"]
    Recipe --> Step1["1. Jump Up! 🤸"]
    Recipe --> Step2["2. Clap Hands! 👏"]
    Recipe --> Step3["3. Shout Hooray! 🎉"]

In Python, we define a function using the word def (short for define):

def celebrate():
    print("Jump Up! 🤸")
    print("Clap Hands! 👏")
    print("Hooray! 🎉")
python

Now, the robot knows the recipe, but it won’t cook it yet. To make the robot run the actions, we must call the function by writing its name with parentheses ():

celebrate()
python

Functions with Ingredients (Parameters)#

Some recipes need ingredients. For example, if you bake a cake, you can choose if it is chocolate or strawberry.

In functions, we call these ingredients Parameters. We put them inside the parentheses:

def greet(name):
    print("Hello, " + name + "! Welcome to our team! 🤝")
python

Now, when we call the function, we send the ingredient inside:

greet("Alex")
greet("Emma")
python

The robot will say:

  • “Hello, Alex! Welcome to our team! 🤝”
  • “Hello, Emma! Welcome to our team! 🤝”

Getting a Result Back (return)#

Sometimes, we want the function to do a calculation and hand the result back to us (like a vending machine giving us a soda), instead of just printing it. We use the return keyword for this:

def double_number(number):
    return number * 2
python

Now, we can save the returned result in a variable box:

magic_number = double_number(5)
print(magic_number) # The robot prints 10
python

Try It Yourself! 🎮#

Open your Python editor and try creating a custom spell command:

  1. Define a function named cast_spell that takes one parameter spell_name.
  2. Inside, make the robot print: "Abrakadabra! You cast " + spell_name + "! ⚡".
  3. Call the function with "Fireball" and then with "Invisibility".

Congratulations! You have completed the 5-part Python series for kids. You now know how to talk to computers, save variables, make decisions, repeat actions, and write custom commands. You are officially a junior coder! 🎉 Keep practicing and building fun things!

References#