livepython.net
CHAPTER 15Python Functions
15.3  RETURN

Python return Statement: Get a Value Back

What Does return Do in Python?

The return statement sends a value back from a function to the line that called it. The call then becomes that value, and you can use it like any other value.

Think of it like a vending machine: you put coins in (the arguments), and it hands a snack back to you (the return value). What you do with the snack is up to you.

PYTHONedit me
def square(n):
    return n * n

result = square(4)
print(result)
print(square(3) + square(2))
OUTPUT
16
13

square(4) becomes 16, so result = square(4) stores 16. In the last line, square(3) becomes 9 and square(2) becomes 4, and 9 + 4 is 13.

The rules

  • Write return, then the value to send back: a number, a string, a variable, or a whole calculation.
  • The value goes back to where the function was called.
  • Nothing is printed unless you print it.

You've used return values before

Many built-in functions return a value: len("Sunny") gives back 5, int("7") gives back 7, and input() gives back the text the user typed. That's why you could write age = int(input()). Now your own functions can do the same:

PYTHONedit me
def add(a, b):
    return a + b

total = add(10, 5)
print("Total:", total)
print("Double:", add(total, total))
OUTPUT
Total: 15
Double: 30

Common beginner doubt: "Does return need brackets, like return(a + b)?" No. return is a keyword, not a function. Brackets work, but return a + b is the usual style.

return hands a value back to the caller; the call becomes that value.

your turnPredict the output

What will this print?

def triple(n): return n * 3 x = triple(4) print(x + 1)
Your turn! What will this code show on the screen?
your turnFill the gap

Make half() give back its answer

def half(n): ? n / 2 print(half(9))

It should print: 4.5

Which piece makes this code work?

Python return vs print

Both seem to "give" you a result, but they're very different. print() shows a value on the screen, for a person to read. return hands the value back to your code, so the program can keep working with it.

Think of it like a calculator: the screen shows you the answer (print), and the memory button keeps it so you can use it in the next sum (return).

print()return
Who gets the value?the person looking at the screenthe line that called the function
Can you store it in a variable?noyes
Does it end the function?noyes

Avoid: printing when you need the value

PYTHONedit me
def add(a, b):
    print(a + b)

total = add(2, 3)
print(total * 2)
OUTPUT
5
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

The 5 appears, so it looks fine. But add() didn't give anything back, so total holds no number, and the multiplication fails. NoneType means "nothing came back". You'll see why at the end of this page.

Good: return the value

PYTHONedit me
def add(a, b):
    return a + b

total = add(2, 3)
print(total * 2)
OUTPUT
10

Which one should a function use?

  • A function that works something out (a total, an area, a grade) should return it. The caller decides what to do with it: print it, store it, or use it in another calculation.
  • A function whose job is to show something (a line, a menu, a report) can print.

Common beginner doubt: "If I return a value, why doesn't it appear on the screen?" Because returning isn't showing. Python passes the value back quietly. Wrap the call in print() when you want to see it.

print shows a value to a person; return gives it back to your code.

your turnPick the right idea

A function works out a bill total. Later, the program adds tax to that total. What should the function do with the total?

Think about it, then pick one.
your turnPredict the output

What will this print?

def double(n): return n * 2 double(5) print("done")
Your turn! What will this code show on the screen?

Using a Returned Value

A returned value is a value like any other. You can store it, print it, use it in a calculation or an if, or pass it straight into another function.

Think of it like the change a shop gives you: you can keep the coins, spend them, or give them to a friend.

PYTHONedit me
def area(length, width):
    return length * width

room = area(4, 5)
print(f"Room: {room} m2")
print(f"Two rooms: {area(4, 5) * 2} m2")
if area(3, 3) > 8:
    print("Big enough")
OUTPUT
Room: 20 m2
Two rooms: 40 m2
Big enough

Where a returned value can go

You writeWhat happens
room = area(4, 5)stored in a variable
area(4, 5) * 2used in a calculation
if area(3, 3) > 8:used in a condition
print(area(2, 3))passed to another function

Return True or False

A function can return a boolean, and then it reads like a question in an if. Names like is_even or has_space make that clear:

PYTHONedit me
def is_even(n):
    return n % 2 == 0

print(is_even(10))
if not is_even(7):
    print("7 is odd")
OUTPUT
True
7 is odd

n % 2 == 0 is already True or False, so you can return it directly. No if needed.

Return two values

Write two values after return, with a comma. Python gives them back as a tuple (chapter 14), and you can unpack it into two variables:

PYTHONedit me
def lowest_and_highest(numbers):
    return min(numbers), max(numbers)

low, high = lowest_and_highest([4, 9, 2])
print(low, high)
OUTPUT
2 9

A returned value can be stored, calculated with, checked in an if, or passed on.

your turnType the output

Type what this prints

def add(a, b): return a + b print(add(add(1, 2), 3))
Read the code line by line, then type the output exactly.
your turnOrder the lines

Put the lines in order to print Welcome

  1. def is_adult(age):
  2. print("Welcome")
  3. if is_adult(20):
  4. return age >= 18
These lines are mixed up. Put them back in order, then press Check.

return Ends the Function Early

When Python reaches a return, the function stops right there. The rest of its lines don't run. This lets you return early: give back an answer as soon as you know it.

Think of it like a shop: once you've found what you came for, you go to the till and leave. You don't walk through the rest of the aisles.

PYTHONedit me
def check_age(age):
    if age < 0:
        return "Invalid age"
    if age >= 18:
        return "Adult"
    return "Child"

print(check_age(-3))
print(check_age(30))
print(check_age(9))
OUTPUT
Invalid age
Adult
Child

For -3, the first return runs and the function ends: the other checks are never looked at. No elif or else needed.

The rules

  • A function can have several return lines. The first one Python reaches wins.
  • Lines after a return in the same block never run.
  • A return inside a loop stops the loop and the function, like break with an answer.

Return from a loop

PYTHONedit me
def first_long_word(words):
    for word in words:
        if len(word) > 5:
            return word
    return "none found"

print(first_long_word(["sun", "banana", "cherries"]))
print(first_long_word(["sun", "sky"]))
OUTPUT
banana
none found

As soon as banana is found, the function hands it back. cherries is never checked. The last return, after the loop, runs only when the loop finds nothing.

Avoid: code after return

PYTHONedit me
def greet():
    return "Hi"
    print("This never prints")

print(greet())
OUTPUT
Hi

No error, but the second line of the body is dead code: it can never run. Delete it, or move it above the return.

The first return Python reaches ends the function. Use it to answer early.

your turnPredict the output

What will this print?

def size(n): if n > 10: return "big" return "small" print(size(10))
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

def first_negative(nums): for n in nums: if n < 0: return n return 0 print(first_negative([3, -2, -5]))
Read the code line by line, then type the output exactly.

A Function Without return Gives None

Every function gives something back. If it has no return, or a return with nothing after it, it gives back None, the "no value" from chapter 5.

Think of it like a waiter who takes your order to the kitchen but never comes back with a plate: you're left with nothing in your hands.

PYTHONedit me
def say_hi():
    print("Hi!")

result = say_hi()
print(result)
OUTPUT
Hi!
None

say_hi() prints, but it returns nothing. So result is None.

In chapter 5 you were promised an answer to "Why does print() show None sometimes?" Here it is: print() itself has no return value, so printing a print gives None:

PYTHONedit me
print(print("Hello"))
OUTPUT
Hello
None

The inner print() shows Hello and gives back None. The outer print() shows that None.

The rules

  • No return at all: the function gives back None.
  • return on its own: the function stops and gives back None.
  • A return in only some paths: the other paths give back None.

Common mistake: forgetting one path

PYTHONedit me
def result(marks):
    if marks >= 50:
        return "Pass"

print(result(80))
print(result(30))
OUTPUT
Pass
None

For 30, the if is False, the function reaches its end, and gives back None. The fix: add return "Fail" as the last line of the body, so every path gives back a value.

Common beginner doubt: "Is a function that returns None broken?" Not at all. A function whose job is to print, like draw_line(), doesn't need to give anything back. Just don't try to use its result.

No return means the function gives back None. Make every path return a value when you need one.

your turnPredict the output

What will this print?

def hello(): print("hello") print(hello())
Your turn! What will this code show on the screen?
your turnFix the code

Fix sign() so it prints: negative

It should print: negative

def sign(n):
    if n >= 0:
        return "positive"

print(sign(-4))
This code does not work yet. Fix it, then press Run.
your turnPredict the output

Remember dictionaries?

ages = {"Sunny": 25, "Rocky": 30} print(ages["Rocky"])
Your turn! What will this code show on the screen?

Practice: return

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 135.Python Program to Convert Celsius to Fahrenheit Using a FunctionEasySolve
  2. 136.Python Program to Find the Largest of Three Numbers Using a FunctionMediumSolve
  3. 137.Python Program to Check a Prime Number Using a FunctionMediumSolve