Python Functions for Kids: Name a Trick and Reuse It

ยท 2 min read ยท By the Tiny Coderz team

Think about teaching a dog to "sit." You do not explain every muscle movement each time. You say one word, and the dog knows the whole trick. A function is the same idea for code: you give a group of instructions a name, then use the name whenever you want those instructions to run.

Your first function

def say_hello():
    print("Hello!")
    print("Welcome to my program.")

say_hello()
say_hello()

Let us read it piece by piece:

  • def means "I am defining a new function."
  • say_hello is the name we chose.
  • The brackets () and the colon : are required.
  • The indented lines are the body, the instructions that belong to the function.

Defining a function does not run it. It is like writing a recipe. The recipe only gets cooked when you call it by writing say_hello(). Here we call it twice, so the message prints twice.

Giving a function something to work with

Functions get more useful when you can hand them information. These pieces of information are called parameters.

def greet(name):
    print("Hello,", name)

greet("Maya")
greet("Leo")

The same function now greets different people. Inside the function, name acts like a variable that holds whatever you passed in.

Getting an answer back

Some functions calculate something and give the result back using return:

def double(number):
    return number * 2

answer = double(21)
print(answer)

This prints 42. Using return is the difference between a function that shows something and one that hands you a value to use later.

Why bother?

Functions help in three big ways:

  1. Less repeating. Write the code once, use it many times.
  2. Easier fixing. If there is a bug, you fix it in one place.
  3. Clearer thinking. A big program becomes a few well-named pieces. This is the idea behind breaking big problems into small ones.

Try these challenges

  1. Write a function called cheer that prints three cheering lines.
  2. Write square(number) that returns the number multiplied by itself.
  3. Write shout(word) that prints the word in capital letters. Hint: strings have a method called .upper().
  4. Write a function that takes a list and prints every item using a loop. (See Python lists for kids.)

Common stumbles

  • Forgetting the indent. Everything inside the function must be indented.
  • Defining but never calling. If nothing happens, check that you wrote the call.
  • Mixing up print and return. If you get None back, the function probably printed instead of returned.

Do not rush this one. Functions are a real step up in abstract thinking, and a child who understands them is well prepared for any language. The Python course introduces them in small steps with plenty of practice.

Try Python Fundamentals with your child

Every lesson in Python Fundamentals opens with an animated explanation, then a short practice. You can read a full sample lesson with no account.

Keep reading