Functions That Return a Value: return
The return statement sends the result a function has calculated back to where it was called. With it we build complex programs from small functions.
All topics (9 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
A function does not have to stop at printing; it can also return the result of a calculation. The return statement does this: inside def square(x): we write return x * x. When we call y = square(5), the result 25 is stored in y. The result can be used in further calculations: print(square(3) + square(4)).
As soon as return runs, the function ends and the lines after it are not executed. That makes it handy inside conditions: in def sign(x): we write if x > 0: return 1, if x < 0: return -1, and then return 0. If there is no return, the function returns None (no value).
Several values can be returned separated by commas: return a + b, a * b; we receive them as s, p = calc(3, 4). Logical functions return True or False, for example def is_even(n): return n % 2 == 0. Such a function can be used directly in a condition: if is_even(8):.
Functions can call one another. For example, max3(a, b, c) can use max2(a, b) inside. Splitting a complex task into small functions makes a program clearer and lets us test each part separately. Do not forget to write a short comment describing what the function does.
Key takeaways
returnsends the result back to the caller and ends the function.- Without
returna function returnsNone. - A function can return
True/Falseand be used in a condition. - Functions call one another, splitting a complex task into parts.
Practice tasks
- Let
def cube(x):return the cube of a number; check the result ofprint(cube(3)). - Write a function
bigger(a, b)that returns the larger of two numbers usingif, and use it to find the largest of three numbers. - Write a function
is_prime(n)that returnsTrueif n is prime andFalseotherwise (test divisibility by numbers from 2 to n-1).
Review questions
Test yourself: think first, then reveal the answer.
1What is the difference between `print()` and `return`?Show answerHide answer
`print()` shows a value on the screen, while `return` gives it back to the program so the result can be stored in a variable and used later.2Are the lines written after `return` executed?Show answerHide answer
No, `return` ends the function immediately.
0 of 11 topics completed
Sign in to mark