Functions
Define reusable code with parameters and return a result.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
A function groups instructions under a name. Parameters receive values when the function is called. The body runs only when you call the function.
return sends a value back to the caller. print only displays a value; it does not make that value the function's result. Names created inside a function are normally local to it.
- Define with def
- Pass arguments into parameters
- return a reusable result
See it step by step
Read the code, predict the output, then compare it with the result.
01. Return a greeting
def greet(name):
return f"Hi, {name}!"
print(greet("Maya"))Hi, Maya!The argument Maya becomes the local name parameter. return sends the finished string back to print().
02. Reuse a calculation
def triple(number):
return 3 * number
print(triple(4))
print(triple(7))12
21One function can be called with different arguments without repeating the calculation.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Define def double(value): and return value * 2 from inside it. After the definition, call double(9) inside print().
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Printing instead of returning
def double(value):
print(value * 2)
result = double(4)
print(result)def double(value):
return value * 2
result = double(4)
print(result)What happens: The function prints 8, but result is None.
Use return when callers need to store or reuse the calculated value.
Missing required argument
def greet(name):
print(f"Hi, {name}")
greet()def greet(name):
print(f"Hi, {name}")
greet("Maya")What happens: TypeError because name was not supplied.
Provide one argument for each required parameter.