Returning a value
Some functions give something back. input gives back the text the user typed, len gives back a length and int gives back a number. Python replaces the call with that value, which you can store in a variable or use in a calculation:
count = len("hello") + 1
The value a function gives back is its return value. Your own functions give one back with the return statement:
def double(number):
return number * 2
result = double(21)
print(result)
print(double(5) + 1)
42
11double prints nothing itself. It works out number * 2 and returns it, and the code that called it decides what to do with it: the first call stores it in result, the second adds 1 to it.
return ends the function
A return ends the function right away, even in the middle of a loop or an if. That makes it easy to return different values in different cases:
def sign(number):
if number > 0:
return "positive"
if number < 0:
return "negative"
return "zero"
print(sign(15))
print(sign(-3))
print(sign(0))
positive
negative
zeroFor 15 the first return runs and the function is over: the lines below it never run for that call. Only when neither condition is true does Python reach the last line. One call runs exactly one return.
A function can return anything: a number, a string, True or False. Here the function reads a number, so the code that uses it stays short:
def ask_number(prompt):
return int(input(prompt))
width = ask_number("Width: ")
height = ask_number("Height: ")
print("Area:", width * height)
4
5Width: 4
Height: 5
Area: 20A return without a value
A plain return, with no value after it, just ends the function. It's handy in a function that prints, to stop early when there's nothing sensible to do:
def print_ratio(a, b):
if b == 0:
print("Can't divide by zero")
return
print(a / b)
print_ratio(7, 2)
print_ratio(7, 0)
3.5
Can't divide by zeroIn a function task, the checks call your function and show what it returns the way the interpreter does: 42 for a number, 'positive' with quotes for a string.