Functions and return
Your own function, parameters and the return value.
A function is a named piece of code that can be called many times. It is declared with def, the parameters go in brackets, and the result is returned with return:
def area(width, height):
return width * height
print(area(3, 4)) # 12
The body of the function is an indented block. The code inside runs only when the function is called, not when it is declared. A function has to be declared before the program calls it.
return ends the function at once and hands the value back to the caller. If there is no return, or it has no value, the function returns None. Hence a common beginner mistake:
def double(x):
x * 2
print(double(4)) # None
The product is computed and immediately lost: nobody returned it.
print and return are different things. print shows a value to a person on the screen, while return hands it to the program: the result can be stored in a variable, compared or passed on. The checks for function tasks look precisely at the returned value.
A good function does one thing, and its name says what: calculate_total, is_valid_email. Functions that answer "yes" or "no" are usually named with is_ or has_ and return True or False. There is no need to write if n > 0: return True else: return False: you can write return n > 0 straight away.
The first line of the body can be a documentation string in triple quotes. help(area) shows it, and editors display it in hints.
Practice
A forgotten return
What does the program print?
def double(x): x * 2 print(double(4))print or return
A function has to hand back its result so that it can be added to another number. What should it use?
- return
- input
- pass
Even or odd
Write a function is_even(n) that returns True for an even number and False for an odd one. Do without if: return the result of a comparison.