🎓 A1Learner
🔍

Python Return Values

A return value is a value a function hands back to the code that called it. return also ends the function at once.

Return a value

The word return hands the answer back. The caller can then print it.

def double(number):
    return number * 2

print(double(4))

Return stops the function

Lines after return in the same block never run. The function has already ended.

def pick():
    return "first"
    print("never")

print(pick())

No return means None

This function only prints. It hands back None, the value that means no value.

def say_hi():
    print("Hi")

result = say_hi()
print(result)

Return two values

Two returned values travel together as a tuple. Two variables can unpack them, one value each.

def pair():
    return 3, 7

low, high = pair()
print(low, high)

Use the result

A returned value can join an expression. Here the result grows by one before printing.

def double(number):
    return number * 2

print(double(4) + 1)

Example

def min_max(numbers):
    smallest = numbers[0]
    largest = numbers[0]
    for number in numbers:
        if number < smallest:
            smallest = number
        if number > largest:
            largest = number
    return smallest, largest

scores = [72, 95, 60, 88]
low, high = min_max(scores)
print("Lowest:", low)
print("Highest:", high)

Key points

  • Use return to hand a value back to the code that called the function
  • Return also ends the function at once
  • Use a returned value in an expression, or save it in a variable
  • A function with no return hands back None
  • print shows a value, but return hands the value back for later use.

In this example, min_max starts with the first score as both smallest and largest. The loop checks each score in turn. A smaller score replaces smallest. A larger score replaces largest. The return line hands back both values together. The call unpacks them into low and high. The last two lines print both ends of the list.

Note

print and return do different jobs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does a function with no return statement hand back?