One exit is enough
A function returns at the first return it reaches. You rarely need more than one, and a single clear exit is easier to follow than several.
A function can hand back a value with return. That value is what the call becomes, so it can be stored or printed.
About 1 min of reading
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Return a value and use it.
Define a function that returns a doubled number.
Before you run it, say out loud what it will print. Then open the answer.
Call it inside a print.
Before you run it, say out loud what it will print. Then open the answer.
Store the result in a name.
Before you run it, say out loud what it will print. Then open the answer.
Call a function that only prints and store it.
Before you run it, say out loud what it will print. Then open the answer.
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
A function returns at the first return it reaches. You rarely need more than one, and a single clear exit is easier to follow than several.
print shows a value to the reader. return gives a value back to the program. A function that only prints cannot be used in a calculation, which is the mistake beginners make most.
def double(n):
return n * 2
print(double(5))
return hands the value back to the call. double(5) becomes 10, and print shows it.
def double(n):
return n * 2
answer = double(4)
print(answer)
The returned value is stored in answer like any other value. A function is a way to make a value you do not write down.
def shout(text):
print(text.upper())
result = shout("hi")
print(result)
A function with no return prints but gives back None. Storing its result stores None, which is the difference between showing and returning.
def first(n):
return n
print("never")
print(first(1))
Code after a return never runs. return is the exit, so the print below it is dead.
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.