Python Functions · Lesson 64 of 149

Python Function Arguments and Return Values

What you will learn

  • How arguments are matched to parameters by position
  • The errors for too many, too few and repeated arguments
  • What a function can do with a list or a number you pass in
  • Changing the input versus returning a new value
  • Passing a function as an argument

1. Parameters and arguments

Two words that are easy to mix up:

Word Where Example
parameter the name in the def line base and exponent in def power(base, exponent):
argument the value you give in the call 2 and 3 in power(2, 3)

The arguments are matched to the parameters by position: the first argument goes to the first parameter, the second to the second:

def power(base, exponent):
    return base ** exponent

print(power(2, 3))
print(power(3, 2))
8
9

power(2, 3) is 2 ** 3, and power(3, 2) is 3 ** 2. Changing the order changes the meaning. That is easy to forget when the parameters have the same type:

def full_name(first, last):
    return f"{first} {last}"

def bmi(weight_kg, height_m):
    return round(weight_kg / height_m ** 2, 1)

print(full_name("Rina", "Hoque"), full_name("Hoque", "Rina"))
print(bmi(70, 1.75), bmi(1.75, 70))
Rina Hoque Hoque Rina
22.9 0.0

Swapping the two arguments of bmi gave 0.0 and no error, because both are numbers. Python cannot check that you meant them in the right order. Good parameter names and keyword arguments (lesson 11.3) help.

Quick check: in `def f(a, b):`, which are the parameters and which are the arguments in `f(10, 20)`?

a and b are the parameters; 10 and 20 are the arguments.

2. Wrong number of arguments

The number of arguments must match the parameters:

def total(a, b, c):
    return a + b + c

total(1, 2)
TypeError: total() missing 1 required positional argument: 'c'
Call Error
total(1, 2) total() missing 1 required positional argument: 'c'
total(1, 2, 3, 4) total() takes 3 positional arguments but 4 were given
total() total() missing 3 required positional arguments: 'a', 'b', and 'c'

The message names the function and the missing parameter, so it points straight at the problem. When the values are already in a list, a star spreads them into separate arguments (lesson 8.3):

print(total(1, 2, 3), total(*[1, 2, 3]))
6 6

3. Any expression can be an argument

An argument can be a name, a calculation, or another call. Python works it out before the function starts:

print(power(2, 10) + power(3, 3))
print(power(power(2, 2), 2))
1051
16

The first line is 1024 + 27. In the second, power(2, 2) gives 4, and the outer call is power(4, 2).

4. What the function receives

When you call a function, each parameter becomes a new name for the same object that you passed (lesson 2.7). Nothing is copied. What that means depends on whether the object can change.

Mutable objects: the function can change them

A list (or a dictionary or set) can be changed in place, and the caller sees the change:

def add_item(items, item):
    items.append(item)

data = ["a"]
result = add_item(data, "b")
print(result, data)
None ['a', 'b']

add_item changed the very list the caller holds, and returned None. Both the caller's data and the function's items are names for one list.

Rebinding does not reach the caller

Assigning a new object to the parameter only moves the function's own name:

def rebind(items):
    items = ["new"]
    return items

data = ["a"]
print(rebind(data))
print(data)
['new']
['a']

The function made a brand-new list and pointed items to it. The caller's data is untouched.

Immutable objects: nothing to change

Numbers, text and tuples cannot be changed in place, so a function can never alter them for the caller (lesson 2.6):

def inc(n):
    n += 1
    return n

x = 5
print(inc(x), x)
6 5

n += 1 made a new number for n. The caller's x is still 5.

5. Change the input, or return a new value?

Because of the two behaviours above, a function that works on a list has two possible styles:

Style Example The caller's list
changes the input items.append(item), returns None is changed
returns a new value return items + [item] stays the same
def with_item(items, item):
    return items + [item]

data = ["a"]
new = with_item(data, "b")
print(data)
print(new)
['a']
['a', 'b']

The second style is safer: a function that does not change its input has no hidden effects, and the caller keeps the original. The first style is fine for operations that are about changing, such as list.append or sort, but then it should return None and its name and documentation should say so (lesson 11.8). Do not mix both: a function that changes its input and returns it invites mistakes.

6. What can be returned

A function can return any kind of value: a number, text, a list, a tuple (for several results), None, even another function (lesson 11.10). It may even return different types in different cases:

def describe(n):
    if n < 0:
        return "negative"
    return n

print(describe(-1), describe(5))
negative 5

This works, but it is hard to use: the caller must check what came back. Prefer a function that always returns the same kind of thing.

A function that returns several values gives a tuple, which you unpack (lessons 8.2 and 11.1):

def swap(a, b):
    return b, a

p, q = swap(1, 2)
print(p, q)
2 1

7. Passing functions as arguments

A function is a value like any other (lesson 11.7), so you can pass one to another function. This lets you separate "what to do" from "how to repeat it":

def apply_twice(f, x):
    return f(f(x))

def add3(n):
    return n + 3

print(apply_twice(add3, 10))
print(apply_twice(str.upper, "a"))
16
A

apply_twice(add3, 10) is add3(add3(10)), which is 16. Notice that you pass add3 without brackets: you give the function itself, and apply_twice calls it. You have already done this with sorted(..., key=len) and map(str, ...).

8. Functions that work for several types

The def line does not state a type. So the same function works on anything that supports the operations inside it:

def mean(values):
    return sum(values) / len(values)

print(mean([4, 8, 6]), mean((1, 2)), mean({3, 5}))
6.0 1.5 4.0

A list, a tuple and a set all work, because sum and len accept all three. This is called duck typing: if it behaves like the thing you need, it will do. If it does not, you get an error at the line that fails.

Worked example: clamping and counting

Write two small functions and use them together. clamp keeps a value between a low and a high limit, and count_words counts the words of a text.

def clamp(value, low, high):
    return max(low, min(value, high))

def count_words(text):
    return len(text.split())

print(clamp(15, 0, 10), clamp(-5, 0, 10), clamp(5, 0, 10))
print(count_words("the quick brown fox"), count_words(""), count_words("  a  b "))

scores = [105, 42, -3, 77]
print([clamp(s, 0, 100) for s in scores])
10 0 5
4 0 2
[100, 42, 0, 77]
Call Why
clamp(15, 0, 10) min(15, 10) is 10, and max(0, 10) is 10
clamp(-5, 0, 10) min(-5, 10) is -5, and max(0, -5) is 0
count_words(" a b ") split() ignores the extra spaces (lesson 4.4), leaving 2 words
the list comprehension calls clamp on every score

Both functions return their results and change nothing outside, which makes them easy to test and reuse. The scores are made up.

Common mistakes

  • Passing the arguments in the wrong order, especially when they have the same type.
  • Expecting the function to change the caller's number or text. Only mutable objects can be changed in place.
  • Expecting items = [...] inside a function to change the caller's list. It only rebinds the name.
  • Forgetting that a function that changes its input returns None.
  • Mixing the two styles, changing the input and also returning it.
  • Passing f() when you meant f. Brackets call the function and pass its result.

Key takeaways

  • Parameters are the names in def; arguments are the values in the call, matched by position.
  • Too few or too many arguments give a TypeError that names the function and the missing parameter.
  • Parameters are new names for the same object: a function can change a list in place, but cannot change a number or text.
  • Assigning to a parameter only rebinds the function's own name.
  • Prefer functions that return a new value and leave the input alone; pass a function without brackets to give it to another function.

Practice

1. What does power(5, 2) give for the function above? And power(2, 5)?

Show answer

25 and 32. The first argument is the base and the second the exponent.

2. What is x after x = 3, def f(n): n += 10; return n, then f(x)?

Show answer

x is still 3. The function changed only its own n, and numbers cannot be changed in place.

3. Write add_all(items, extra) that returns a new list with the extra items added, leaving items unchanged.

Show answer
def add_all(items, extra):
    return items + list(extra)

4. Why does def f(items): items = [1] not change the caller's list?

Show answer

The assignment points the parameter name items at a new list. The caller's name still points to the old list.

5. What error does power(2) give, and what does it mean?

Show answer

TypeError: power() missing 1 required positional argument: 'exponent'. One argument is needed for each parameter.

6. In sorted(words, key=len), why is len written without brackets?

Show answer

sorted needs the function itself so that it can call it on each item. len() would call it at once, with no argument, and give an error.