I have been learning Python for some days now. However, I do not understand return. I have read several explanations from my textbooks and online; they don\'t help!
return
returns a value from a function:
def addseven(n):
return n + 7
a = 9
b = addseven(a)
print(b) # should be 16
It can also be used to exit a function:
def addseventosix(n):
if n != 6:
return
else:
return n + 7
However, even if you don't have a return
statement in a function (or you use it without specifying a value to return), the function still returns something - None
.
def functionthatisuseless(n):
n + 7
print(functionthatisuseless(8)) # should output None
Sometimes you might want to return multiple values from a function. However, you can't have multiple return
statements - control flow leaves the function after the first one, so anything after it won't be executed. In Python, we usually use a tuple, and tuple unpacking:
def addsevenandaddeight(n):
return (n+7, n+8) # the parentheses aren't necessary, they are just for clarity
seven, eight = addsevenandaddeight(0)
print(seven) # should be 7
print(eight) # should be 8
return
statements are what allow you to call functions on results of other functions:
def addseven(n):
return n+7
def timeseight(n):
return n*8
print(addseven(timeseight(9))
# what the intepreter is doing (kind of):
# print(addseven(72)) # 72 is what is returned when timeseight is called on 9
# print(79)
# 79