Python Function Parameters and Arguments
Parameters and Arguments in Python
A parameter is a name in the brackets of a def: a variable that waits for a value. An argument is the value you put in the brackets when you call the function.
Think of it like a form with a blank: "Hello, ____!" The blank is the parameter. What you write in it is the argument.
def greet(name):
print(f"Hello, {name}!")
greet("Sunny")
greet("Rocky")Hello, Sunny! Hello, Rocky!
One function, two different greetings. The argument changes, the function stays the same.
| In the def | In the call |
|---|---|
the parameter name | the argument "Sunny" |
| a blank to fill in | the value that fills it |
The rules
- When you call
greet("Sunny"), Python doesname = "Sunny"at the start of the body. - An argument can be any value: a string, a number, a list, or a variable.
- The parameter only exists inside the function (more on that in topic 4).
- You met this idea in chapter 2:
sepandendare parameters ofprint().
The argument can come from a variable, even one with a different name, or from input():
def greet(name):
print(f"Hello, {name}!")
user = input()
greet(user)Hello, Lucky!
Avoid: leaving out the argument
def greet(name):
print(f"Hello, {name}!")
greet()TypeError: greet() missing 1 required positional argument: 'name'
Don't be scared of this error! It's saying: greet() needs a value for name, and you didn't give one. Put the value in the brackets.
Parameters are the blanks in the def; arguments are the values you fill in when you call.