LESSON 09 · BEGINNER PATH11 min

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

PYTHON
def greet(name):
    return f"Hi, {name}!"

print(greet("Maya"))
EXPECTED OUTPUT
Hi, Maya!

The argument Maya becomes the local name parameter. return sends the finished string back to print().

02. Reuse a calculation

PYTHON
def triple(number):
    return 3 * number

print(triple(4))
print(triple(7))
EXPECTED OUTPUT
12
21

One 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 run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnCreate a function named double that returns twice its argument. Call it with 9 and print the result.
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.

    01.What does square(3) return when square uses return value * value?

    02.What is the return value of a function with no return statement?

    03.What does a parameter do?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Printing instead of returning

    COMMON MISTAKE
    def double(value):
        print(value * 2)
    result = double(4)
    print(result)
    FIX
    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

    COMMON MISTAKE
    def greet(name):
        print(f"Hi, {name}")
    greet()
    FIX
    def greet(name):
        print(f"Hi, {name}")
    greet("Maya")

    What happens: TypeError because name was not supplied.
    Provide one argument for each required parameter.