Course contentsLesson 7 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 07

Functions and return values

Edit lesson

Give a reusable operation a name, pass it inputs, and return a result.

18 minProgress saves on this device
In this lesson
  • Define and call a function
  • Distinguish parameters from arguments
  • Return a value to the caller

Helpful background: Understand variables, decisions, and loops.

Define and call a function

A function groups instructions under a name. def introduces the function, followed by parameters in parentheses and an indented body.

The body runs when you call the function. An argument is the value passed to a parameter in that call.

Define a functionpython
def greet(name):
    print(f"Hello, {name}!")

greet("Mira")
greet("Sam")

Return a result

return sends a value back to the caller and ends the function. Printing shows a value; returning lets the caller store it, combine it, or test it.

A function that reaches the end without an explicit return returns None.

Return a valuepython
def area(width, height):
    return width * height

room_area = area(4, 3)
print(room_area)  # 12

Defaults and names

A parameter can have a default used when the caller omits that argument. Local names created inside a function are separate from names in the caller.

Avoid using a mutable object such as a list as a default argument unless you intend to share it between calls.

Use a defaultpython
def greeting(name, prefix="Hello"):
    return f"{prefix}, {name}!"

print(greeting("Mira"))
print(greeting("Sam", prefix="Welcome"))

Keep responsibilities clear

Give a function one clear job and a name that describes it. Test normal cases and boundary cases, such as zero or an empty list, when those inputs are valid.

Knowledge check

What does return do inside a function?

Try first; feedback appears after you check.
Apply it

Your turn

Write a function that returns the total price for a quantity and a price per item.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson