Functions: Creating Robot Commands
Teach your Python robot new tricks! Learn how to bundle code blocks into custom buttons called functions, use inputs, and return results.
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.
- Defining the Recipe (
def): You write down the steps of the recipe once. - 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! 🎉")pythonNow, 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()pythonFunctions 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! 🤝")pythonNow, when we call the function, we send the ingredient inside:
greet("Alex")
greet("Emma")pythonThe 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 * 2pythonNow, we can save the returned result in a variable box:
magic_number = double_number(5)
print(magic_number) # The robot prints 10pythonTry It Yourself! 🎮#
Open your Python editor and try creating a custom spell command:
- Define a function named
cast_spellthat takes one parameterspell_name. - Inside, make the robot print:
"Abrakadabra! You cast " + spell_name + "! ⚡". - 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!