← Python lessons

Defining Functions

A function is a named, reusable block of code. Defining it describes a job; calling it runs that job.

Define a function

Use def, a name, parentheses and a colon. Indent the body by four spaces.

def show_greeting():
    print("Hello!")
    print("Welcome to Python.")

This defines show_greeting but prints nothing: its body has not run yet.

Call it by name

Put parentheses after the name to run the function.

def show_greeting():
    print("Hello!")

show_greeting()
show_greeting()

Each call prints Hello!. Reusing the function avoids copying its body. Writing show_greeting without parentheses refers to the function but does not call it. The definition must have run before you call it.

Give the job a useful name

Use lowercase words separated by underscores, such as show_greeting or print_menu. Choose a name that explains the job instead of function1.

pass is a placeholder statement that does nothing. Replace it with the function body when completing an exercise.

Your turn

Define show_ready() to print Ready!, then call it twice.

# Define the function and call it twice (four lines).

Expected output

Ready!
Ready!

A function can also receive values and send a result back. Continue with Parameters & Return before tackling a function exercise that takes arguments or returns a value.

See also: Printing Output, Decomposition.


Practise this in the free Python course, where every exercise checks your code instantly.