Card 12: Functions

Module 5: Reusable Code

1 The Hook

Think about a TV remote.

You press "Power". You don't need to know how the electronics confirm the signal, activate the circuit, and light the screen.
You just press the button, and it does the job.

Functions are like buttons. We group code together, give it a name (the button), and press it whenever we need it.

2 Worked Example

Defining and Calling a routine.

# 1. Define the Button (Function)
def warn_user():
print("Warning!")
print("System Overload")
# 2. Press the Button (Call)
warn_user()

PREDICT

Order matters. What prints first?

def alpha():
  print("A")

def beta():
  print("B")

beta()
alpha()

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Chorus Line

1. Look at the function sing().
2. Change the code inside so it prints 3 lines: "La", "La", "La".
3. Run it to hear the song.

> _
SILVER (FIX)

🥈 The Silent Function

This code defines a function to start the engine, but nothing happens when you run it!
1. Fix it by Calling the function at the bottom.
2. Add start_engine() (don't forget the brackets!).

> _
GOLD (MAKE)

🥇 Game Loop

1. Define a function called game_over().
2. Inside, print "Game Over" and "Try Again".
3. Call the function 3 times to annoy the player.

> _