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.
def square(n):
return n * n
result = square(4)
print(result)
print(square(3) + square(2))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:
def add(a, b):
return a + b
total = add(10, 5)
print("Total:", total)
print("Double:", add(total, total))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.