Sub topic 2
Parameters and Arguments
This chapter assumes you can define a simple function with def, call built-in functions such as print and len, and work with lists, tuples and dictionaries. It covers the vocabulary of function inputs, what Python does when you call a function, and the errors you see when a call does not match its definition. Chapters on keyword arguments, defaults, *args and **kwargs, and / and * build on this model.
Two words for one flow of data
Every function that takes input has two sides. The definition names the inputs it expects. The call supplies actual values for them.
| Term | Where it appears | What it is |
|---|---|---|
| Parameter | In the `def` line | A variable name that the function uses for an input |
| Argument | In the call | The value (an object) you supply for a parameter |
def greet(name, punctuation): # name and punctuation are parameters
return f"Hello, {name}{punctuation}"
print(greet("Ada", "!")) # "Ada" and "!" are argumentsPeople often use the two words interchangeably, and most readers will understand you. The distinction still matters when you read error messages and documentation. Python's messages say "missing 1 required positional argument" because the call is the thing that is short.
What a call does
When Python runs greet("Ada", "!"), it follows these steps:
- It evaluates each argument expression, left to right, and gets an object for each.
- It creates a new local scope for this call.
- It binds each parameter name in that scope to the matching argument object.
- It runs the function body.
- It discards the local scope when the body finishes, unless something such as a closure still refers to it.
Step 3 is the core of the model. A parameter is an ordinary local variable whose first value comes from the caller. Nothing about it is special once the body starts running.
Arguments are evaluated before the call
An argument can be any expression: a literal, a variable, arithmetic, or another function call. Python finishes evaluating all of them before the function body starts.
def noisy(label):
print("evaluating", label)
return label
def show(a, b):
return a, b
result = show(noisy("first"), noisy("second"))
print(result)This prints evaluating first, then evaluating second, then ('first', 'second'). The function show never sees the expressions, only the resulting objects. This is why a call like show(len(items), items[0]) raises an error in the caller's line if items is empty, before show runs.
Matching arguments to parameters
Python must be able to pair every parameter with exactly one argument. The simplest pairing is by position: the first argument goes to the first parameter, the second to the second, and so on. You can also name the parameter in the call (punctuation="!"), which the next chapter covers fully.
If the call and the definition do not fit together, Python raises a TypeError before running any of the body. The following script triggers the four most common mismatches and prints each message.
def greet(name, punctuation):
return f"Hello, {name}{punctuation}"
bad_calls = [
lambda: greet("Ada"),
lambda: greet("Ada", "!", "extra"),
lambda: greet("Ada", punctuation="!", mood="happy"),
lambda: greet("Ada", name="Grace"),
]
for call in bad_calls:
try:
call()
except TypeError as error:
print(error)On a current Python 3 release the output is:
greet() missing 1 required positional argument: 'punctuation'
greet() takes 2 positional arguments but 3 were given
greet() got an unexpected keyword argument 'mood'
greet() got multiple values for argument 'name'The exact wording varies a little between versions, but the four situations are the same:
| Message says | Cause | Fix |
|---|---|---|
| missing N required positional argument | Fewer arguments than required parameters | Supply the missing value or give the parameter a default |
| takes N positional arguments but M were given | More positional arguments than parameters | Remove the extra value or add a parameter |
| unexpected keyword argument | You named a parameter that does not exist | Check the spelling against the definition |
| multiple values for argument | One parameter received a value twice, by position and by name | Pass it once |
The fourth case surprises people. In greet("Ada", name="Grace"), "Ada" fills the first parameter by position, and then name="Grace" tries to fill it again.
Parameters are names, not copies
Binding a parameter does not copy the argument. The parameter name and the caller's variable refer to the same object. Whether that matters depends on whether the object can change.
def append_one(items):
items.append(1) # changes the shared list
def replace_list(items):
items = [0] # rebinds the local name only
numbers = []
append_one(numbers)
print(numbers) # [1]
replace_list(numbers)
print(numbers) # [1]append_one calls a method that mutates the list, so the caller sees the change. replace_list assigns a new list to the local name items. That affects only the local scope, and the caller's numbers still refers to the original list. With immutable objects such as numbers, strings and tuples, no function can change the object in place, so the question of shared change does not arise.
This is a short preview. The chapter on how arguments are passed covers it in detail, including why it leads to the mutable default argument bug.
Rebinding a parameter is allowed
Because a parameter is a normal local variable, you can assign to it inside the function.
def normalize(text):
text = text.strip()
text = text.lower()
return text
original = " Hello "
print(normalize(original)) # hello
print(repr(original)) # ' Hello 'Each assignment rebinds the local name text to a new string. The caller's original is untouched because strings are immutable and the assignments never modify an existing object. Reusing a parameter name this way is legal and common, though a new variable name can make longer functions easier to read.
Annotating parameters with type hints
You can attach a type hint to each parameter and to the return value. Hints document what the function expects, and tools such as editors and type checkers read them.
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3)) # 5
print(add("2", "3")) # 23Python does not check hints when the function runs. The second call passes strings, breaks the hint, and still works because + joins strings. A type checker such as mypy would flag that call before you run it. Treat hints as documentation that a tool can verify, not as validation.
Common errors and how to avoid them
- Confusing definition and call. Writing
def greet("Ada")is aSyntaxError, because thedefline takes parameter names, not values. Writinggreet(name)in a call needsnameto exist in the caller as a variable, or you get aNameError. - Forgetting parentheses.
greetby itself refers to the function object and does not call it. Onlygreet("Ada", "!")runs the body. - Expecting changes to flow back. Rebinding a parameter never changes the caller's variable. To give a new value to the caller, return it and assign the result.
- Mutating an argument by accident. Methods such as
append,sortandupdatechange the caller's object. If the function should not do that, work on a copy such asitems = list(items). - Counting arguments wrongly after a refactor. When you add a parameter to a definition, every existing call needs updating. A search for the function name finds them. The error message will also point to each one when the code runs.
Checking your understanding
Exercise
A function is defined as def area(width, height):. Name the parameters and the arguments in the call area(3, 4 + 1), and say what value height has inside the function.
Show answer
The parameters are width and height. The arguments are 3 and 4 + 1. Python evaluates 4 + 1 to 5 before the call, so height is bound to 5 and width to 3.
Exercise
Given def label(kind, value):, which of these calls raise a TypeError, and why? (a) label("id", 7) (b) label("id") (c) label("id", 7, 8) (d) label("id", kind="name")
Show answer
(a) works. (b) raises a TypeError because value is missing. (c) raises a TypeError because three positional arguments were given for two parameters. (d) raises a TypeError because kind receives a value both by position ("id") and by keyword, and value is also missing.
Exercise
What does this code print, and why? def reset(values): values = [] data = [1, 2, 3] reset(data) print(data)
Show answer
It prints [1, 2, 3]. The assignment values = [] rebinds the local name to a new list and does not modify the list that data refers to. To empty the caller's list, the function would need to mutate it, for example with values.clear().