Python Function Arguments
Arguments let you feed data into a function, and Python offers several styles for supplying them so your calls stay clear and flexible.
Positional arguments
The simplest way to pass values is by position. Python matches each argument to a parameter based on its order: the first argument fills the first parameter, the second fills the second, and so on. Because order determines meaning, swapping two positional arguments usually changes the result.
Order matters with positional arguments
def introduce(name, role):
print(name + " works as a " + role)
introduce("Asha", "designer") # Asha works as a designer
introduce("designer", "Asha") # designer works as a AshaKeyword arguments
You can also pass values by naming the parameter directly in the call using the name=value form. These are called keyword arguments. Because each value is tied to a name rather than a position, the order no longer matters and the call reads more clearly.
Naming arguments explicitly
def introduce(name, role):
print(name + " works as a " + role)
introduce(role="engineer", name="Ravi")
# Ravi works as a engineerDefault parameter values
A parameter can be given a default value in the definition. If the caller omits that argument, the default is used; if they supply one, it overrides the default. Defaults are useful for options that rarely change, so callers only specify what differs from the norm.
A default makes an argument optional
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Maya") # Hello, Maya!
greet("Maya", "Good morning") # Good morning, Maya!Rules to keep in mind
- By default, you must pass one argument for every parameter that has no default value.
- Positional arguments must appear before any keyword arguments in a call.
- Avoid using mutable objects such as lists or dictionaries as default values, since the same object is shared across calls.
- Keyword arguments make calls with many parameters far easier to read.