Functions

A free sample lesson from Python Fundamentals

The idea

A function is a trip to a side room to do one specific, repeatable job, then walking back out to exactly where you left off in the story. You define the trip once with def name():, and every time you call name(), Python takes that same trip again. Whatever happens inside the side room stays inside it, unless you explicitly bring something back out.

What it actually is

A function is a named, reusable block of code you define once and can run (call) as many times as you like, instead of copying the same lines over and over.

How you write it

def function_name():
    # code that runs each time it's called

function_name()   # this actually runs it

A worked example

def cheer():
    print("You can do it!")

cheer()
cheer()

def cheer(): defines the function but doesn't run it yet - it's just a recipe. Each separate cheer() call on the last two lines actually runs that recipe, which is why 'You can do it!' gets printed twice.

def announce():
    print("Level up!")

announce

Referring to a function by name without parentheses (announce) points at the function itself - it never runs it. Only calling it with parentheses (announce()) actually performs the code inside; leaving them off is a common silent mistake, since Python does not error, it simply does nothing.

Mistakes children actually make

Mistake 1: forgetting the parentheses when calling it - writing cheer instead of cheer() refers to the function itself (as an object) without ever running it, so nothing prints. Mistake 2: assuming def cheer(): ... runs the code immediately - defining a function only teaches Python the recipe; it does nothing until it's actually called. Mistake 3: calling a function before its def block has run yet (e.g. earlier in the file) - Python reads top to bottom, so the function has to be DEFINED before the line that calls it, or it crashes with NameError, since it doesn't exist yet as far as Python knows.

Then they try it

In the app this lesson continues with the animated explanation, spoken aloud, and then the practice: Change what happens on the trip to the side room so it prints 'Hello, Coder!' instead of 'Hello!'. The editor runs your child’s real code and checks the result, with their coding buddy reacting to what they wrote.

Try it free