Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 149 ยท Functions

Return Values

Learn how Python functions send results back with return, how to return several values as a tuple, why early returns simplify code, and when you get None.

A function that only prints is like a calculator that shows the answer on its screen but won't let you copy it. The return statement hands a value back to the code that called the function, so the caller can store it, combine it with other values or pass it on to another function.

In this lesson you'll learn what return does, how to send back several values at once, how an early return keeps code flat and readable, and why a function without return quietly gives you None. If you haven't met def yet, start with Functions.

Returning a value

When Python reaches a return statement, two things happen at once: the function stops running, and the value after return becomes the value of the call expression. Wherever you wrote area(3, 4), Python substitutes the result.

Python A function that returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The -> float after the parameter list is a type hint that documents what the function returns. Python doesn't enforce it, but editors and readers find it helpful. You'll learn more in Type Hints.

Beginners often mix up print() and return because both seem to "produce" a value. They are very different:

  • print() writes text to the screen for a human to read. The program can't do anything else with that text.
  • return gives a value back to your program. Nothing appears on screen unless you print it yourself.
Python print is not return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

a is None because shout_print never returns anything. b holds the real string, so you can repeat it, store it in a list or send it to another function. As a rule, let functions return results and do the printing in one place, usually near the top level of your program. Functions that return values are easier to test and reuse.

Code after return never runs

return ends the function immediately. Any lines after it in the same block are unreachable:

Python
def greet(name):
    return f"Hello, {name}"
    print("This line never runs")

Linters flag code like this, and it's almost always a mistake. A loop is no exception: a return inside a for loop leaves both the loop and the function on the spot.

Returning several values

A function can return only one object, but that object can be a tuple. Write several values separated by commas after return, and Python packs them into a tuple. The caller can then unpack them into separate names:

Python Multiple return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Returning a tuple works well for two or three closely related values. If you find yourself returning five or six, or the caller keeps forgetting which position means what, return a dictionary, a named tuple or a data class instead, so each value has a name.

Tip: The built-in divmod(17, 5) is a good example of this pattern. It returns (3, 2): the quotient and the remainder together.

Early returns

A function can contain several return statements. The first one Python reaches wins. This lets you handle special cases at the top and leave as soon as you know the answer, a style often called guard clauses:

Python Guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare that with the same logic written as deeply nested if/else blocks. Guard clauses keep the "normal" path at the left edge of the code, where it's easiest to read.

Early returns are also natural in search loops. As soon as you find what you're looking for, return it; if the loop finishes without a match, return a fallback after the loop:

Python
def first_negative(values):
    for value in values:
        if value < 0:
            return value
    return None

Functions that return None

Every Python function returns something. If execution reaches the end of the body without hitting return, or hits a bare return with no value, the function returns None.

Python The implicit None

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Methods that change an object in place, such as list.sort(), list.append() and dict.update(), return None on purpose. It's a reminder that they modified the original instead of building a new object. If you want a sorted copy, use the built-in sorted(scores), which returns a new list.

Watch out: A function that returns a value on some paths and falls off the end on others is a common source of bugs. If one branch returns a number and another forgets to return, the caller suddenly gets None and crashes later with a confusing TypeError. When any path returns a value, make every path return one explicitly.

Checking for None

When None means "no result", check for it with is None, not with == and not with plain truthiness. A truthiness check treats 0, "" and [] as missing too, which is usually wrong:

Python
match = first_negative([3, 0, 8])
if match is None:
    print("No negative numbers")

Returning conditions directly

A comparison already produces True or False, so a function that answers a yes-or-no question rarely needs an if statement. Instead of this:

Python
def is_adult(age):
    if age >= 18:
        return True
    else:
        return False

return the condition itself:

Python
def is_adult(age: int) -> bool:
    return age >= 18

The short version is easier to read and can't accidentally return the wrong value from one branch. Functions like this, whose names start with is_, has_ or can_, make if statements read like sentences: if is_adult(age):.

Returning functions and other objects

Because everything in Python is an object, a function can return a list, a dictionary, a class instance or even another function. Returning a function is the foundation of closures and decorators, which you'll meet soon in Scope and Decorators:

Python Returning a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice return multiply has no parentheses. You're handing back the function object so the caller can call it later.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this code print? def f(): print(3) then x = f() and print(x)

    Calling f() prints 3, but the function has no return, so it returns None, which is what x holds.
  2. 2. What does return a, b actually return?

    The comma creates a tuple. The caller can unpack it with x, y = func().
  3. 3. What happens to code placed after a return in the same block?

    return exits the function immediately, so the following lines are unreachable. Python allows it, but linters warn about it.
  4. 4. Why does numbers = numbers.sort() leave numbers set to None?

    In-place methods return None by design. Use sorted(numbers) to get a new sorted list, or call numbers.sort() on its own line.
  5. 5. Which is the safest way to check whether a function returned "no result"?

    is None matches only None. not result would also treat 0, empty strings and empty lists as missing.

Summary

  • return value ends the function and makes value the result of the call.
  • print() shows text to a person; return hands a value back to your program. Prefer returning.
  • return a, b, c returns a tuple, which the caller can unpack into separate names.
  • Several return statements are fine: guard clauses handle special cases first and keep the main path flat.
  • A function without return, or with a bare return, returns None. In-place methods like list.sort() return None on purpose.
  • Make every path return a value if any path does, and check for "no result" with is None.

Next: Scope: Local, Global and Nonlocal, where you'll learn where variable names live and how closures remember values.