Tutorial 12/15 REUSABLE CODE

Python: Functions

Grouping code together and giving it a name.

The Hook

Think about a TV remote.

You press "Power". You don't need to know the circuit logic; you just press the button and it does the job.

Functions are like buttons. We group instructions, name the "button", and press it whenever we need it!

Worked Example

Defining and Calling a warning routine.

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

Predict Output

Order matters! What prints first?

def alpha():
  print("A")

def beta():
  print("B")

beta()
alpha()
Level 31: Bronze

Chorus Line

"Change the sing() function to print 'La' three times."

> bronze_stream_standby
Level 32: Silver

Silent Function

"The engine define but never runs. Call the function at the bottom of the code."

> debugger_module_monitoring
Level 33: Gold

Game Loop

Independent Construction Pattern

  • Define a function called game_over().
  • Inside, print "Game Over" and "Try Again".
  • Call the function three times at the bottom.
> computation_vector_online