Python Arena
Step 1 of 5

Your own functions

You have called plenty of functions already: print, input, int, len. They come with Python. Now you'll write your own. A function is a named piece of code: you write it once, and then run it whenever you need it, by its name.

Defining a function

def greet():
    print("Hello!")
    print("Nice to see you.")

A function definition starts with the keyword def (short for define), then the function's name, a pair of parentheses and a colon. This first line is the function's header. Under it, indented like the body of an if or a while, comes the function's body: the code that runs when the function is used.

Run that program and nothing happens. That's not a mistake: def only defines the function, that is, it tells Python what the name greet means. The body runs only when the function is called.

Calling a function

To call a function, write its name with parentheses after it, as you do with print:

def greet():
    print("Hello!")
    print("Nice to see you.")


greet()
print("...")
greet()
Output
Hello!
Nice to see you.
...
Hello!
Nice to see you.

Python reads the definition and remembers the function. Then each call runs its body, once per call. A function can be called as many times as you like: that's the point of writing one.

Function names follow the same rules as variable names: small letters, with underscores between words, such as print_menu. Leave two empty lines after a function definition, before the code that comes after it; Python doesn't need them, but they make the program easier to read, and Python programmers expect them.

Functions on this site

From now on, many tasks ask you to write a function. The checks call your function themselves, so your program needs only the definition, with no calls of its own and no input. A test named greet() calls greet() and compares what it prints with what it should print. To try your function with Run, you can add a call under the definition; the checks look only at what their own calls print.

The starter code of a function task often has pass as the body. pass is a statement that does nothing. A body can't be empty, so pass holds the place until you write the real code. Replace it with your own lines.

Your task

Challenge 1 of 3

Fill in the blank so the program defines a function cheer that prints Hip hip hooray! when it's called.

Challenge 2

Write a function print_menu() that prints this menu:

1. Start
2. Settings
3. Quit

Challenge 3

What does this program print? Type each line it prints.