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.")print("Defined.")Only Defined. prints. The def creates show_greeting, but 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.
Note: A function can also receive values and send a result back. Read Parameters & Return before a function exercise that takes arguments or returns a value.
See also: Printing Output, Decomposition.
Your turn
Define show_ready() to print Ready!, then call it twice.
Ready! Ready!
# Define the function and call it twice (four lines).Advanced reading
- Docstrings — describe what a function does and read it back with
help(). - Functions as values — store, pass and return functions, and build closures.
- Lambda functions — write a small one-line function without
def.