return, explained simply
Some functions do a job, like printing a message. Others work something out and hand the answer back. That is what return is for.
When Python reaches return, it leaves the function straight away and gives back the value after it. You can store that value in a variable, print it, or use it in more maths.
print() only shows something on the screen. return gives the value back to your program. A function that prints an answer cannot be used in a calculation; one that returns it can.
Example: Work out a cost
def bridge_cost(planks):
return planks * 15
small = bridge_cost(4)
big = bridge_cost(10)
print(small + big)Output
210Try this
- Change return to print inside the function and see what small + big does now.
- Write a function that returns the bigger of two numbers.
- Add a line after return inside the function. Does it ever run?
