← All missions

πŸ§ͺ Invent Your Own Powers

🎨 Reusable Code & Art

1) What do I need to do?

🎯 Your mission: Sound the alarm

Make a function called alarm that prints 3 lines of alarm messages.

Call it twice.

2) What do I need to know?

def makes a new command

A function is a set of instructions with a name. You've used built-in ones like print() and len().

With def you can invent your own! def hero_entrance(): β€” then indent the lines that belong to it.

Defining it doesn't run it. You call it by writing its name with brackets: hero_entrance()

🧰 Your toolkit for this mission

Everything you need to know to finish this lesson on your own:

Function

A named set of instructions you can use again and again.

How to write it: def name(): then indent the instructions underneath.

def alarm():
    print("ALERT!")
    print("Villain spotted!")

Calling a function

Defining only teaches Python. Calling actually runs it.

How to write it: Write the name with brackets, not indented: alarm().

alarm()
alarm()

Order

Define a function before you call it.

How to write it: Put def blocks near the top of your code.

Think about it

Look at this code. What happens next, and why? Say it in your own words.

zap()
zap()
Watch & explore β–Ά

Power-up: def makes a new command

See it happen

1 / 3
def zap():
    print("Zap!")
πŸ“ recipe
zap

def teaches Python a new command. It does not run the recipe yet.

3) Run the code & terminal output

Code Lab 🐍Playground β€” experiment freely!
Hero Terminal

Press β–Ά RUN and your program's messages appear here!

Power Workshop
Power Workshop
Your superhero companion

Captain Py

Our next adventure is yours to create.