Intro to Computer Science / Unit 7: Functions
7.3 Return Values
Notes
The return statement sends a value back to the caller and ends the function. print only displays a value.
def square(n):
return n * n
result = square(6)
print(result)
- This prints
36. The returned value is stored inresult. - Code after a
returnin the same function does not run. - A function with no
returngives backNone. - Returned values can be used in calculations:
square(3) + square(4)is9 + 16 = 25.
Practice
What does
def f(x): return x + 1 followed by print(f(f(3))) display?f(3) is 4, then f(4) is 5.
What does
def g(n): print(n * 2) followed by y = g(4); print(y) show at the end?The function prints 8 but returns nothing, so y is None.
What does
def h(): return 1; print(2), when h() is called, do with the print line?Anything after return in the same block is skipped.
Ready for more? Take the Unit 7 test.