Defining and Calling Functions
Learning Objectives
- You can define a function using
defand call it. - You can trace a program, distinguishing a function definition from the execution of its body.
- You can place function definitions and the main program in a clear order.
- You can identify repeated code or a distinct task that could be given a function name.
You have called functions since your first Python program:
print("Hello")length = len("hello")A function call asks Python to run behavior that has been defined somewhere. Until now, almost all of those definitions came from Python itself.
You can define your own functions too.
Your First Function
The output is:
Hello!Welcome to the program.The definition begins with def:
def greet():The colon starts an indented block, just as it does with if, for, and while. The indented lines form the function body.
The function body does not run merely because Python reads the definition. It runs when the function is called:
greet()Read that line as:
Run the function named
greet.
The parentheses are part of the call. They will become more important in the next chapter, when functions begin receiving information.
Defining Is Not Calling
Before running this program, predict whether inside greet appears before or after after definition:
The output is:
before definitionafter definitioninside greetafter callWhen Python reaches:
def greet():it creates the function definition and continues past the body. The body is saved for later. Only the call greet() makes Python enter the function and execute its lines.
A useful trace is:
- print
before definition; - define
greet; - print
after definition; - call
greet; - execute the body and print
inside greet; - return to the line after the call;
- print
after call.
This idea matters whenever you read a larger program. Function definitions often appear near the top, but their bodies may run much later.
Trace a few definitions and calls before writing your own:
Now define and call one small function yourself:
Prepare a launch display
0 / 10 points
Define a function named show_launch_display with empty parentheses because it does not receive information when called. Its body must print these two lines:
LAUNCH CONTROLREADYAfter the definition, call show_launch_display() exactly once. Keep the display output inside the function body; the call in the main program is what makes it appear.
The complete program must produce exactly the two lines shown above.
Calling a Function More Than Once
Once behavior has a name, it can be reused:
def print_separator(): print("--------------------")
print("First section")print_separator()print("Second section")print_separator()print("Third section")The two calls execute the same body at different points in the program.
This is one reason functions help with duplicated code. If the separator later changes, there is one definition to edit instead of several copied lines.
But avoiding duplication is not the only reason to use a function. A function name can also make the structure of a program easier to see.
Compare:
print("--------------------")print("SUMMARY")print("--------------------")with:
print_separator()print("SUMMARY")print_separator()The second version tells a reader what the repeated lines are for.
Use repeated calls to keep one visual detail in one place:
Arrange a mission dashboard
0 / 10 points
Define a function named show_marker with empty parentheses because it does not receive information when called. It must print exactly ten hyphens:
----------The starter already prints three dashboard labels. Call show_marker() after each label so the complete output is:
FLIGHT PLAN----------CREW----------SUPPLIES----------Keep the marker text in the function and reuse that function three times. Do not copy the marker’s print statement into the main program.
Try calling a function in natural language. Assemble the given definition and body blocks, then write the step that calls the function between the START and END print steps.
Call a function with natural-language programming
0 / 5 points
This exercise combines given blocks with a step you write in natural language. Drag blocks from “Available blocks” into “Program”. To write your step, first drag the blank block into “Program”, then type in its editable box. The editor automatically translates your program into Python; inspect “Generated Python” before submitting.
Assemble a function called print_separator that takes no arguments and prints one separator line, ”---”, each time it is called. Drag the function definition block into “Program”, then place the given “Print ’---’.” block inside its function body.
After the definition, place the START and END print blocks outside the function body. Between these two blocks, write a natural-language step that calls print_separator.
The complete program must print these three lines in this order, with no additional output:
START---ENDFunctions as Named Pieces of Work
The measurement program in the overview had four jobs: read input, select usable values, calculate a summary, and present the result. A function can give one of these jobs a name.
For example, a program that collects values and displays the usable ones might later look like this:
values = read_values()usable = select_usable(values)print(usable)This is a design sketch, not a complete runnable program: read_values and select_usable have not been defined here. The next chapter explains how functions return values. For now, notice that the names let you follow the program’s tasks without reading all the code for each one.
Do not create a function merely because a block contains several lines.
A useful function usually represents a meaningful piece of work: calculate a total, classify a value, read one item, format one part of a report, or display one kind of message.
Choose functions that make the program’s tasks easier to understand.
A Definition Must Run Before Its Function Is Called
When Python executes a call, the function name must already refer to a function. At the top level of a program, this normally means Python must execute the function’s def statement before it reaches the call.
This does not work:
greet()
def greet(): print("Hello")When the first line runs, Python does not yet know what greet refers to.
A common structure is therefore:
def greet(): print("Hello")
def print_separator(): print("----------")
print_separator()greet()print_separator()Function definitions appear first. The main program comes afterwards. This is a useful program structure, not a rule that every function body must appear earlier than every call written anywhere in the file. What matters is whether the definition has executed by the time Python executes the call.
You will see this structure repeatedly throughout the rest of the course.
Common Mistakes
Forgetting the parentheses when calling
This:
greetdoes not run the body. greet refers to the function itself. greet() calls it.
Forgetting the colon
def greet() print("Hello")is invalid syntax. The definition line ends in a colon.
Incorrect indentation
def greet():print("Hello")The body must be indented.
Defining but never calling
This program produces no output:
def greet(): print("Hello")The function exists, but nothing asks it to run.
Repair each of these mistakes in a complete program:
Finally, explain the chapter’s central distinction in your own words:
Explain a two-stage program
0 / 10 points
Explain in plain language what Python does when it executes this program:
def show_signal(): print("Signal received")
print("Waiting")show_signal()In three or four sentences, distinguish defining show_signal from calling show_signal(). Explain when the function body runs and give the two output lines in their execution order.
Check Your Understanding
- What is the difference between defining a function and calling it?
- How do the colon and indentation identify a function’s body?
- Where does execution continue after a function call finishes?
- What must have happened before Python can call a function by its name?
- When would it be useful to give a piece of work its own function name?
AI Study Aid
Create a chapter diagram
We're looking into to what extent AI-generated diagrams could help with studying.
Use this study aid to generate an AI-generated visual summary of the material you just studied.
Each diagram style emphasizes the content in a different way, so you can choose the focus
that feels most useful.
Using the diagram generator is voluntary and does not affect your course progress. We encourage
you to try it out and see if it helps, but it's totally up to you! Your answers help us understand
how to make better study aids in the future.