print and return do different jobs. print shows a value on the screen. return hands a value back to the caller so the program can keep working with it.
The difference shows when you try to use the result:
def double_with_print(n):
print(n * 2)
result = double_with_print(4)
print(result)
Output:
8
None
The first line, 8, appeared because the function printed it. But result is None because a function without a return returns None, a special value meaning "nothing". The computed 8 was shown and then lost. result + 1 would be an error.
With return, the value survives:
def double(n):
return n * 2
result = double(4)
print(result + 1)
Output:
9
Best practice: return the value, and let the caller decide whether to print it. From here on, every exercise function returns its result unless the instructions say otherwise.
The starter code defines area, but it prints instead of returning, so the last line prints None.
area so it returns width * height.print(area(3, 4)) line. The output should be 12 — and no None.Run your code to see the output, then press Submit.
import unittest
class TestArea(unittest.TestCase):
def test_area_returns_a_value_instead_of_none(self):
self.assertIsNotNone(area(3, 4))
def test_area_of_3_by_4_is_12(self):
self.assertEqual(area(3, 4), 12)
def test_area_of_5_by_5_is_25(self):
self.assertEqual(area(5, 5), 25)
def area(width, height):
return width * height
print(area(3, 4))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.