Print or Return?
Beginners often mix up return and print(), because both seem to give a value out. But they do very different things:
print()only shows a value to you, in the output. The program can't work with what was printed.returngives the value to the program, which can store it, calculate with it or print it.
Look at what happens when a function prints its result instead of returning it:
def print_sum(a, b):
print(a + b)
result = print_sum(2, 3)
print(result)This prints:
5
NoneThe 5 was printed by the print() inside the function. But the function didn't return anything, and a function without return returns None: a special value in Python that means “nothing”. So result is None, and the second print() prints None.
When you try to calculate with None, the program ends with an error:
def print_sum(a, b):
print(a + b)
total = print_sum(2, 3) * 2This prints:
5
Traceback (most recent call last):
File "<exec>", line 4, in <module>
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'The error message says that * can't work with None (whose type is NoneType) and a whole number (int). Whenever you see None or NoneType where you expected a value, check whether your function has a return.
It can also happen the other way round: a function returns a value, but nobody uses it:
def add(a, b):
return a + b
add(2, 3)This program prints nothing. The function returned 5, but the program didn't store it or print it, so the value was lost. If you want to see it, print it: print(add(2, 3)).
So when should a function print, and when should it return? A function that calculates something should return the result. The code that calls it then decides what to do with it: print it, store it or keep calculating with it. Print inside a function only when showing something is its whole job, like in say_hello() or print_area().
Instructions
A pizza costs 9 and a drink costs 3. The function order_price should calculate the price of an order, but the program prints two prices and then ends with the error TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'. Fix the function: return the price instead of printing it. The program then prints Together: 63.
At the end of the program, compare the two orders: if the family pays less than the friends (family < friends), print The family pays less.
Start programming for free
6/10