Writing Your Own Functions · practice
Parameters and Arguments
The
def greet(name):
print(f"Hello, {name}!")
The name inside the definition’s parentheses is a parameter:
def greet(name):
# ^ parameter
It is a
greet("Mina")
# ^ argument
The value in the call is an
Use the words consistently:
A parameter is a variable named in a function definition.
An argument is a value supplied in a function call.
People sometimes use the words loosely, but this distinction makes it much easier to explain what code is doing.
One definition, different arguments
Each call creates a new run of the function body. During the first call, name holds "Mina". During the second, it holds "Jon".
The function does not need a separate version for every person. Its parameter describes the part that may change.
More than one parameter
Separate parameters with commas:
def show_score(player, points):
print(f"{player} scored {points} points.")
Calls supply one argument for each parameter:
show_score("Maya", 8)
show_score("Omar", 11)
By default, Python matches them by position:
| Position | Parameter | First call’s argument |
|---|---|---|
| first | player | "Maya" |
| second | points | 8 |
Reversing the arguments still produces valid Python, but the message no longer makes sense:
show_score(8, "Maya")
# 8 scored Maya points.
The function can only work with the meaning you give each position.
Choose parameters that belong to the job
A parameter should be information the function genuinely needs. describe_trip needs a person’s name and a destination, so two parameters make sense.
It does not need every variable in the program. Passing unrelated information makes a function harder to understand and call correctly.
This is your first small design decision: identify what changes from call to call, and make that information a parameter.
In the code below, which statement is correct?
def show_price(amount):
print(f"Price: {amount}")
show_price(12)
Task
Complete describe_trip so it uses two name and place.
The
Maya is heading to Kyoto.
Keep both calls. The same definition should produce:
Maya is heading to Kyoto.
Omar is heading to Lima.