Python Parameters & ArgumentsGet Certified
What Are Parameters and Arguments?
A function becomes truly useful when it can work with different data each time it runs. Parameters and arguments are the tools that make this possible. They let you send information into a function so that one block of code can greet any student, price any ticket, or total any list of scores.
A parameter is the variable name written inside the parentheses when you define the function. An argument is the actual value you pass when you call the function. In short, parameters are the empty seats and arguments are the people who sit in them. Python offers several ways to match arguments to parameters, and this lesson covers all of them.
- Parameter: a name in the function definition, such as
nameindef greet(name):. - Argument: the value passed in the call, such as
"Emily"ingreet("Emily"). - Positional arguments: matched to parameters by their order.
- Keyword arguments: matched by name, written as
name=value. - Default values: a parameter such as
base=12.50becomes optional. *argsand**kwargs: collect any number of extra positional or keyword arguments.
Positional Arguments
Positional arguments are the simplest and most common way to call a function. Python matches the first argument to the first parameter, the second argument to the second parameter, and so on. The order you write them in is the order Python uses.
If you pass too few or too many positional arguments, Python raises a TypeError. If you pass them in the wrong order, the program still runs but the values end up in the wrong places, which can produce confusing results. Always check the order when a function has several parameters.
Try It: Welcome Visitors to a City
Click Test My Code to run the program. Then change the names and cities to your own friends and hometowns.
name and city, and calls it three times with different American names and cities. Each call prints a welcome message.def welcome(name, city):
print("Welcome,", name, "from", city)
welcome("Emily", "Austin")
welcome("Jackson", "Denver")
welcome("Olivia", "Boston")def welcome(name, city): creates a function with two parameters. These names are placeholders that receive values when the function is called.name and city behave like normal variables. print() separates its items with spaces."Emily" goes to name and "Austin" goes to city, because positional arguments are matched by order. The output is Welcome, Emily from Austin.Welcome, Jackson from Denver.Welcome, Olivia from Boston. One definition handled three different visitors.Default Parameter Values
A default value gives a parameter a fallback to use when the caller does not supply an argument. You write it in the definition with an equals sign, such as base=12.50. The parameter then becomes optional, which keeps simple calls short while still allowing full control.
Parameters with defaults must come after the parameters without defaults. Writing def f(a=1, b): is a SyntaxError. Defaults are ideal for settings that are usually the same, such as a standard ticket price, a tax rate, or a delivery fee.
Try It: Movie Ticket Prices in Chicago
Click Test My Code. Then change the base price or the age limit for the child discount.
def ticket_price(age, base=12.50):
if age < 12:
return base / 2
return base
print(ticket_price(8))
print(ticket_price(30))
print(ticket_price(30, 15.00))age is required. base=12.50 is optional and uses 12.50 when no second argument is given.age < 12 is True for children.return sends the result back to the caller.base uses its default. The output is 6.25.12.5.15.00 replaces the default for this call only. The output is 15.0.Keyword Arguments
With keyword arguments you write the parameter name in the call, as in destination="Dallas". Python matches the value by name, so the order no longer matters. This makes calls easier to read, especially when a function has many parameters.
You can mix both styles in one call, but positional arguments must come first, followed by keyword arguments. Giving the same parameter twice, once by position and once by name, raises a TypeError. Keyword arguments are a good habit whenever a value like True or 15 would be unclear on its own.
Try It: Book Flights Across the U.S.
Click Test My Code. Then book a trip to your favorite city using keyword arguments.
def book_flight(passenger, origin, destination):
print(passenger + ": " + origin + " to " + destination)
book_flight("Madison", "Seattle", "Miami")
book_flight(destination="Dallas", passenger="Ethan", origin="Phoenix")
book_flight("Noah", destination="Atlanta", origin="Portland")+ to make one line of text, such as Madison: Seattle to Miami.Madison: Seattle to Miami.Ethan: Phoenix to Dallas."Noah" is positional and goes to passenger. The remaining values are given by name. The output is Noah: Portland to Atlanta.Any Number of Arguments with *args
Sometimes you do not know in advance how many values a caller will send. Placing a single star before a parameter name, such as *scores, tells Python to collect all extra positional arguments into one tuple. The name args is only a convention, so a descriptive name is better.
Inside the function you can loop over the tuple or pass it to functions such as sum(), max(), and len(). The caller can send zero, one, or fifty values, and the same function handles them all. You can also use a star in a call to unpack a list into separate arguments.
Try It: Total a Basketball Team’s Points
Click Test My Code. Then add more scores to either call.
def team_total(*scores):
print("Scores received:", scores)
return sum(scores)
print(team_total(21, 34, 18))
print(team_total(27, 30))*scores packs every positional argument into a tuple named scores.sum(scores) adds all the values in the tuple and return sends the total back.Scores received: (21, 34, 18) and then the outer print() shows 73.Scores received: (27, 30) followed by 57.Named Extras with **kwargs
Two stars before a parameter name, such as **stats, collect all extra keyword arguments into a dictionary. The names become the keys and the values become the dictionary values. This is perfect for functions that accept optional details, like a profile card or a settings list.
When a function has several kinds of parameters, the order in the definition is: normal parameters, then *args, then keyword-only parameters, then **kwargs. Because **kwargs is a dictionary, you can use items() to loop over it, just as you learned in the Dictionaries lesson.
Try It: Print a Player Card
Click Test My Code. Then add another statistic such as assists=6.
def player_card(name, **stats):
print(name)
for key, value in stats.items():
print(" ", key + ":", value)
player_card("Liam", team="Bulldogs", points=28, rebounds=9)name is a normal parameter. **stats collects every other keyword argument into a dictionary.stats.items() gives each (key, value) pair, such as ("team", "Bulldogs").key: value with a small indent."Liam" goes to name. The three keyword arguments become {'team': 'Bulldogs', 'points': 28, 'rebounds': 9}. The output is four lines: Liam, team: Bulldogs, points: 28, and rebounds: 9.Safe Defaults and Changing Arguments
Two important behaviors catch many beginners. First, when you pass a list or dictionary to a function, the function receives a reference to the same object, so changes inside the function are visible outside. Second, a default value is created only once, when the function is defined.
That second rule means a mutable default such as cart=[] is shared between calls and quietly keeps its old items. The safe pattern is to use None as the default and create a fresh list inside the function. The example below uses this pattern.
Try It: Build a Grocery Cart
Click Test My Code. Then add more items to the shopping cart.
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
print(add_item("apples"))
print(add_item("milk"))
my_cart = ["bread"]
add_item("eggs", my_cart)
print(my_cart)cart is None, not []. This avoids sharing one list between all calls.cart is None is True only when the caller did not supply a cart.append() adds the item to whichever list cart now refers to.['apples'].['milk'], with no leftover apples.my_cart is a list that already holds "bread".my_cart and appends to that same list. The return value is ignored here.['bread', 'eggs']. The original list was changed by the function.Positional-Only and Keyword-Only Parameters
Python lets you control exactly how a parameter may be passed. A forward slash / in the parameter list means every parameter before it must be given by position. A bare star * means every parameter after it must be given by name.
Keyword-only parameters are a great way to prevent mistakes with yes-or-no options. A call such as shipping_cost(2, express=True) is far clearer than shipping_cost(2, True). Many built-in functions, such as print() with its sep and end options, use this idea.
Try It: Shipping Cost from Houston
Click Test My Code. Then change the weight or the price per pound.
express option must be passed by name. Express shipping adds ten dollars.def shipping_cost(weight, /, *, express=False):
cost = 4.00 + weight * 1.50
if express:
cost = cost + 10
return cost
print(shipping_cost(2))
print(shipping_cost(2, express=True))
# shipping_cost(2, True) would raise a TypeErrorweight comes before /, so it is positional-only. express comes after *, so it is keyword-only and defaults to False.if express: runs the next line only when express is True.7.0.express=True is given by name, as required. The output is 17.0.True by position would raise a TypeError, because express must be named.Using Parameters with input()
Parameters and arguments work together nicely with user input. The input() function returns text, which you can split into pieces and convert into values for a function call. This is how many small programs turn typed data into real results.
In this example a star in the call unpacks a list into separate arguments, the reverse of what *args does in a definition. Remember that every piece of input starts as a string, so numbers must be converted with int() or float() before you do math with them.
Try It: Report a Student’s Average
The Program Input box is already filled with one line: Emily 88 92 79. Click Run Code straight away, then try another name and your own scores.
line = input("Name and test scores: ")
parts = line.split()
def report(name, *scores, passing=70):
average = sum(scores) / len(scores)
status = "passing" if average >= passing else "not passing"
print(name, "has an average of", round(average, 1), "and is", status)
report(parts[0], *[int(s) for s in parts[1:]])input() reads the first line of the Program Input box as one string, such as "Emily 88 92 79".split() breaks the string at the spaces into the list ['Emily', '88', '92', '79'].name is a normal parameter, *scores collects any number of scores, and passing=70 is a keyword-only parameter with a default. Parameters after *scores can only be given by name.sum(scores) adds the scores to get 259, and dividing by len(scores), which is 3, gives about 86.33."passing" when the average is at least 70. Otherwise it picks "not passing".round(average, 1) keeps one decimal place. With the default input, the output is Emily has an average of 86.3 and is passing.parts[0] is the name. The comprehension converts the remaining pieces to integers, and the star in front of it unpacks them into separate arguments. Without the star, the whole list would arrive as one argument.Tip: When a function has more than three or four parameters, call it with keyword arguments. The code documents itself, and you cannot mix up the order by accident.
Common Mistakes with Parameters and Arguments
Most argument errors come from a small set of habits that are easy to fix once you know them. Python usually gives a helpful TypeError message that names the function and tells you what is missing or unexpected. Read that message carefully, then compare your call with the definition line.
- Wrong number of arguments: calling
welcome("Emily")when two are required raises aTypeErrorabout a missing argument. - Wrong order:
welcome("Austin", "Emily")runs but prints the city as the name. Use keyword arguments to be safe. - Default before non-default:
def f(a=1, b):is aSyntaxError. Put required parameters first. - Mutable default values:
def add(item, cart=[]):shares one list between every call. UseNoneand create the list inside. - Same argument twice: passing a value by position and by name for the same parameter raises a
TypeError. - Positional after keyword:
f(name="Noah", "Atlanta")is aSyntaxError. Positional arguments come first. - Forgetting the star when unpacking:
report(name, scores)sends one list, whilereport(name, *scores)sends each item separately. - Confusing the two terms: parameters appear in the definition, and arguments appear in the call.
Good Habits for Writing Parameters
Clear parameters make a function easy to understand and reuse, even months after you wrote it. Think of the parameter list as the instructions on the front of a machine. A good list tells the reader what the function needs without making them read the whole body.
- Choose descriptive names such as
passengeranddestinationinstead ofaandb. - Keep the parameter list short. If a function needs many inputs, consider grouping them in a dictionary or a class later.
- Give optional settings a sensible default value, and list required parameters first.
- Never use a list or dictionary as a default. Use
Noneand build the object inside the function. - Use keyword arguments in calls when the meaning of a value is not obvious, such as
express=True. - Do not change an argument in place unless the function name or documentation makes that clear.
Key Takeaways
Parameters and arguments are what turn a fixed block of code into a flexible, reusable tool. Once you can choose the right style for each situation, your functions become shorter, safer, and easier to read. Review the points below before moving on to return values and scope.
- A parameter is a name in the definition. An argument is the value passed in the call.
- Positional arguments are matched by order, and keyword arguments are matched by name.
- Default values make parameters optional. Required parameters must come first.
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- Use
/and*in the definition to require positional-only or keyword-only parameters. - Avoid mutable default values. Use
Noneinstead.
Frequently Asked Questions
Students often ask the same handful of questions when they first meet parameters and arguments. The answers below summarize the most important rules in plain language. Open each question to read the answer, and try the matching example above to see it work.
What is the difference between a parameter and an argument in Python?
A parameter is the variable name listed in the function definition, such as name in def greet(name). An argument is the actual value you pass when calling the function, such as “Emily” in greet(“Emily”). The argument is assigned to the parameter when the function runs.
What are positional and keyword arguments?
Positional arguments are matched to parameters by their order in the call. Keyword arguments are written as name=value and are matched by parameter name, so their order does not matter. In one call, positional arguments must come before keyword arguments.
How do default parameter values work in Python?
A default value is written in the definition, as in def ticket_price(age, base=12.50). If the caller leaves out that argument, Python uses the default. If the caller supplies a value, it replaces the default for that call only. Parameters with defaults must come after those without.
What does *args mean in Python?
A star before a parameter name, such as *scores, collects any number of extra positional arguments into a tuple. This lets one function accept two values, ten values, or none. The name args is only a convention, and a descriptive name is usually clearer.
What does **kwargs mean in Python?
Two stars before a parameter name, such as **stats, collect extra keyword arguments into a dictionary. The argument names become the keys and their values become the dictionary values. It is useful for optional details like team or points.
Why should I not use a list as a default argument?
A default value is created only once, when the function is defined. A list default such as cart=[] is therefore shared by every call and keeps its old items. Use None as the default and create a new list inside the function instead.
Does Python pass arguments by value or by reference?
Python passes a reference to the object. If you pass a mutable object such as a list, changes made inside the function are visible outside. If you pass an immutable object such as a number or a string, the function cannot change the original, because assigning a new value only rebinds the local name.
What do the / and * symbols mean in a function definition?
Parameters before a / must be passed by position only. Parameters after a bare * must be passed by keyword only. For example, def shipping_cost(weight, /, *, express=False) requires weight by position and express by name.