After this lesson you can give a function the data it needs, collect the answer it computes, and choose correctly between print and return.
Parameters and arguments
A function that always does exactly the same thing is of limited use. Parameters let the caller supply the details. You list them inside the parentheses of the def line, and you give the real values when you call the function.
def greet(name):
print("Hello,", name)
greet("Asha")
greet("Ben")Hello, Asha
Hello, BenHere name is the parameter. The text "Asha" is the argument. Each call gives name a different value for the duration of that call.
With more than one parameter, the arguments are matched by position, first to first, second to second.
def line_total(price, quantity):
print(price * quantity)
line_total(40, 3)
line_total(quantity=5, price=10)120
50The second call names the parameters, which is allowed and covered fully in the lesson on keyword arguments.
Returning a value
Printing puts text on the screen. It does not give anything back to your program. To hand a result back to the code that called the function, use return.
def line_total(price, quantity):
return price * quantity
total = line_total(40, 3)
print(total)
print(line_total(2, 5) + line_total(1, 1))120
11The call line_total(40, 3) is replaced by the value it returns, so it can be stored in a variable or used inside a bigger expression. This is the main skill of this lesson: a function that returns can be combined with others.
Print versus return
Beginners often print inside a function when they should return. Compare these two:
def add_printing(a, b):
print(a + b)
def add_returning(a, b):
return a + b
x = add_printing(2, 3)
y = add_returning(2, 3)
print("x is", x)
print("y is", y)5
x is None
y is 5add_printing showed 5 on the screen but handed back nothing, so x is None. add_returning gave back 5, so y holds it. If later code needs the number, you need return. Use print only for the final display to a person.
return ends the function
The moment Python reaches return, the function stops. Lines after it do not run. This is useful for early exits.
def discount_label(age):
if age >= 60:
return "senior discount"
if age < 12:
return "child discount"
return "no discount"
print(discount_label(70))
print(discount_label(8))
print(discount_label(30))senior discount
child discount
no discountEach call runs only as far as the first return it meets.
No return means None
A function that finishes without return gives back a special value called None, which means "nothing here".
def log_sale(item):
print("sold", item)
result = log_sale("tea")
print(result)sold tea
NoneReturning more than one value
A function can return several values separated by commas. Python packs them into a tuple, and the caller can unpack them in one line.
def min_and_max(numbers):
return min(numbers), max(numbers)
low, high = min_and_max([4, 9, 2, 7])
print(low, high)
print(min_and_max([4, 9, 2, 7]))2 9
(2, 9)Checking input inside a function
A function is also a good place to protect against bad input. You can check an argument at the top and return early, or raise an error. This keeps the main logic free of clutter.
def safe_divide(total, parts):
if parts == 0:
return None
return total / parts
print(safe_divide(10, 4))
print(safe_divide(10, 0))2.5
NoneReturning None signals "no answer". The caller must then check for it before using the result, which is something you will see again in the lesson on errors. The important habit is to decide, for every function, exactly what it returns in every situation, and to keep that consistent. A function that sometimes returns a number and sometimes a string forces everyone who calls it to guess.
You can also give a short description of the return value in the docstring, so readers know what to expect without reading the body.
Common mistakes
- Printing when you meant to return. The tell-tale sign is
Noneshowing up where you expected a number. - Writing code after return. It will never run.
- Forgetting to use the result. Calling
line_total(40, 3)on its own computes the value and throws it away. Store it or print it. - Wrong number of arguments. The call must supply a value for every parameter, unless a default exists.
The last point produces a clear error:
def line_total(price, quantity):
return price * quantity
line_total(40)TypeError: line_total() missing 1 required positional argument: 'quantity'Python tells you exactly which argument is missing, so read the message to the end.
Exercise
Write a function average(numbers) that returns the average of a list of numbers, and use it on the marks [70, 85, 90]. The function must return the value, not print it. Then print the result rounded to one decimal place.
Show one possible answer
def average(numbers):
return sum(numbers) / len(numbers)
mean = average([70, 85, 90])
print(round(mean, 1))81.7Key points
- Parameters are names listed in the def line. Arguments are the actual values you pass when you call the function.
- return sends a value back to the caller and ends the function immediately.
- A function with no return statement gives back None.
- printing shows a value on screen, returning hands it to your code. Return when the result will be used again.
- return a, b sends back one tuple, which you can unpack into two names.