Browser lab15 min+60 XP

Your first function

Stop copying and pasting. Give a block of code a name and run it whenever you like.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

Define a function once with def, then call it by name as often as you like.

Key words
show_banner()call 1show_banner()call 2show_banner()call 3def show_banner():code written onceBanner on screenevery time it is called
Three calls all run the same code that was written once.

A function is a named block of code that does one job. You have already used built-in functions like print(), input() and len(). Now you will make your own.

You define a function with def, a name, brackets and a colon. The code inside is indented. Defining a function does not run it. You run it by calling it: writing its name with brackets, like show_banner().

Functions make code shorter (write once, use many times), easier to read (a good name explains what happens) and easier to fix (change it in one place).

Real life linkA "jump" button in a game calls the same jump function every time you press it. Nobody rewrites the jump code for every press.
Example code
def show_banner():
    print("*" * 20)
    print("   WELCOME BACK")
    print("*" * 20)

show_banner()
print("Loading level 1...")
show_banner()
TASK 2

Try it yourself

+10 XP

Define a function called cheer that prints Go team! and then We can do this!. Call it three times.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

Which keyword do you use to define a function?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Border maker

+20 XP

Write a function border() that prints a line of 25 ~ characters. Use it to print a mini poster: a border, the line PYTHON CLUB, the line Thursdays 4pm, and another border.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.