Functions
Define and call functions
Create a function with def and call it when you need its work.
Lesson 24 of 63
Reading: about 2 min
Lesson + practice: about 11 min
Difficulty: Beginner
On this page4 sections
A function groups instructions under a name. def defines the function; its indented body runs only when you call it. Python has built-in functions such as print(), and you can create your own.
def show_welcome():
print("Welcome to Python practice!")
show_welcome()
show_welcome()Welcome to Python practice! Welcome to Python practice!
Why functions help
A function gives repeated work one clear place. Define it before the call in a script so Python has executed the definition by the time you call it.
Why this works
When Python reaches def, it creates a function and associates it with the given name. It does not run the indented body until a call uses that name followed by parentheses. This lets a script reuse the same instructions without copying them into several places.
Practice
Define a function named show_goal that prints your learning goal. Call it twice and check that the message appears twice.
Does defining a function run its indented body immediately?
Reveal answer
No. The body runs when the function is called.
Try another case
If a function is defined once and called three times, how many times does its body run?
Check your answer
Reveal answer
Three times, once for each call.
Your progress
Reveal the check answer or reach the end to complete this lesson.