Giving an answer back with return
print shows a value on the screen. return hands a value back, so the program can store it or use it again. Study circle_area. It has a parameter radius, a local variable pi and the line return pi * radius * radius. The call circle_area(5) gives 78.5, which result stores. The number 3.14 is only an approximation of pi, so the answers are approximate too. A function that only prints gives back None, so the line result = add_print(2, 3) stores None. A function with return gives a real value: result * 2 works. The names pi and radius live only inside the function. Outside it, print(pi) causes a NameError.
1def circle_area(radius): 2 pi = 3.14 3 return pi * radius * radius 4 5result = circle_area(5) 6print(result) 7print(circle_area(10))
78.5 314.0
1def add_print(a, b): 2 print(a + b) 3 4def add_return(a, b): 5 return a + b 6 7result = add_print(2, 3) 8print(result) 9result = add_return(2, 3) 10print(result * 2)
5 None 10
1def triangle_area(base, height): 2 return 0.5 * base * height 3 4print(triangle_area(6, 4))
12.0
1def circle_area(radius): 2 pi = 3.14 3 return pi * radius * radius 4 5print(pi)
NameError: pi exists only inside the function
Write a function celsius_to_f(c) that returns c * 9 / 5 + 32. Work out by hand the result for 25 and for 100. Then write the line that stores the result for 25 in a variable called warm.
1def circle_area(radius): 2 pi = 3.14 3 return pi * radius * radius 4 5result = circle_area(5) 6print(result) 7print(circle_area(10))