Academic Block

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 name in def greet(name):.
  • Argument: the value passed in the call, such as "Emily" in greet("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.50 becomes optional.
  • *args and **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.

What this code does: It defines a function with two parameters, 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")

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.

What this code does: It calculates a movie ticket price. Children under 12 pay half price. The base price has a default of $12.50, but the caller can override it with a different price.
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))

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.

What this code does: It prints a flight booking line three times: once with positional arguments, once with only keyword arguments in a different order, and once with a mix of both.
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")

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.

What this code does: It defines a function that accepts any number of game scores, prints the tuple it received, and returns the total. It is called once with three scores and once with two.
def team_total(*scores):
    print("Scores received:", scores)
    return sum(scores)
print(team_total(21, 34, 18))
print(team_total(27, 30))

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.

What this code does: It prints a player’s name and then loops over any extra keyword arguments, printing each statistic on its own line.
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)

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.

What this code does: It adds items to a grocery cart. When no cart is given, a new one is created for each call. When an existing cart is passed in, the function adds the item to that same list.
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)

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.

What this code does: It calculates a package shipping cost. The weight must be passed by position and the 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 TypeError

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.

What this code does: It reads a student’s name followed by test scores, passes them to a function that accepts any number of scores, and prints the average with a passing or not passing message.
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:]])
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 a TypeError about 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 a SyntaxError. Put required parameters first.
  • Mutable default values: def add(item, cart=[]): shares one list between every call. Use None and 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 a SyntaxError. Positional arguments come first.
  • Forgetting the star when unpacking: report(name, scores) sends one list, while report(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 passenger and destination instead of a and b.
  • 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 None and 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.
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dictionary.
  • Use / and * in the definition to require positional-only or keyword-only parameters.
  • Avoid mutable default values. Use None instead.

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.

Ready for the next step?Learn how functions send results back and where variables can be used.
Next: return, Scope & Lifetime →