Kahibaro
Discord Login Register

Parameters and arguments

Parameters and Arguments

In this chapter, you’ll see how to give information to functions using parameters and arguments. This is what makes functions truly reusable and flexible.

Parameters vs Arguments

When talking about functions:

Think of a function like a machine:

def greet(name):      # 'name' is a parameter
    print("Hello,", name)
greet("Alice")        # "Alice" is an argument
greet("Bob")          # "Bob" is an argument

The function greet is defined with one parameter: name.
Each time you call greet(...), you pass a different argument.

Positional Arguments

The most common type of arguments are positional arguments.
They are matched to parameters by their position (order).

def add(a, b):
    print(a + b)
add(3, 5)   # a = 3, b = 5
add(10, 2)  # a = 10, b = 2

If you change the order, the meaning changes:

def describe_pet(animal, name):
    print("I have a", animal, "named", name)
describe_pet("dog", "Rex")    # animal = "dog", name = "Rex"
describe_pet("Rex", "dog")    # animal = "Rex", name = "dog" (probably wrong!)

With positional arguments, order matters.

Keyword Arguments

Keyword arguments (also called named arguments) use the parameter name when calling the function. This makes your call more explicit and order-independent.

def describe_pet(animal, name):
    print("I have a", animal, "named", name)
describe_pet(animal="dog", name="Rex")
describe_pet(name="Mittens", animal="cat")

In both calls:

Here, the order does not matter, because you specify which value goes to which parameter by name.

You can mix positional and keyword arguments, but:

def introduce(first_name, last_name, age):
    print(first_name, last_name, "is", age, "years old.")
introduce("Alice", "Smith", 20)                 # all positional
introduce("Alice", last_name="Smith", age=20)   # mixed: positional then keyword
# introduce(first_name="Alice", "Smith", 20)    # ❌ not allowed (positional after keyword)

Default Parameter Values

Sometimes you want parameters to have a default value, which will be used if the caller does not provide an argument.

You define default values in the function definition using =.

def greet(name, greeting="Hello"):
    print(greeting + ",", name)
greet("Alice")                  # uses default greeting "Hello"
greet("Bob", "Good morning")    # overrides default greeting

You can also combine positional, keyword, and default parameters:

def make_sandwich(bread, filling="cheese", toasted=False):
    print("Bread:", bread)
    print("Filling:", filling)
    print("Toasted:", toasted)
make_sandwich("white")                         # uses defaults for others
make_sandwich("whole grain", "ham")            # change filling
make_sandwich("white", toasted=True)          # keyword for toasted
make_sandwich("rye", filling="turkey", toasted=True)

Rule about defaults

Parameters with default values must come after parameters without defaults in the function definition:

def example(a, b=10):  # ✅ allowed
    pass
# def wrong_example(a=10, b):  # ❌ not allowed (non-default after default)
#     pass

Multiple Parameters

You can define functions with more than one parameter. Each one needs an argument when calling the function (unless it has a default).

def calculate_total(price, quantity, tax_rate):
    subtotal = price * quantity
    tax = subtotal * tax_rate
    total = subtotal + tax
    print("Total:", total)
calculate_total(10.0, 3, 0.1)         # all positional
calculate_total(price=10.0, quantity=3, tax_rate=0.1)  # all keyword
calculate_total(10.0, tax_rate=0.1, quantity=3)        # mixed with keywords

If a parameter has no default and you do not provide an argument, Python will raise a TypeError.

def show_info(name, age):
    print(name, "is", age, "years old.")
# show_info("Alice")  # ❌ missing argument for 'age'

Variable Number of Arguments: `*args` and `**kwargs`

Sometimes you don’t know in advance how many arguments you’ll need. Python lets you collect a variable number of arguments using args and *kwargs.

`*args` – extra positional arguments

Use *args to accept any number of extra positional arguments. Inside the function, args will be a tuple.

def add_all(*numbers):
    total = 0
    for n in numbers:
        total += n
    print("Sum:", total)
add_all(1, 2)            # numbers = (1, 2)
add_all(1, 2, 3, 4, 5)   # numbers = (1, 2, 3, 4, 5)

*numbers means: “pack all extra positional arguments into a tuple called numbers.”

You can mix normal parameters and *args:

def greet_all(greeting, *names):
    for name in names:
        print(greeting, name)
greet_all("Hello", "Alice", "Bob", "Charlie")

Here:

`**kwargs` – extra keyword arguments

Use kwargs to accept any number of extra keyword arguments. Inside the function, kwargs will be a dictionary**.

def print_settings(**options):
    for key, value in options.items():
        print(key, "=", value)
print_settings(volume=10, brightness=70, theme="dark")

Here, inside the function:

You can mix normal parameters, args, and *kwargs:

def demo(a, b, *args, **kwargs):
    print("a:", a)
    print("b:", b)
    print("args:", args)
    print("kwargs:", kwargs)
demo(1, 2, 3, 4, x=10, y=20)

Call result:

Order of different parameter types

When defining a function, the general order is:

  1. Regular positional parameters
  2. Parameters with default values
  3. *args
  4. **kwargs

Example:

def func(a, b=0, *args, **kwargs):
    pass

Argument Unpacking with `*` and `**`

The and symbols are also used when calling* functions to unpack collections into arguments.

Unpacking a list or tuple into positional arguments

You can pass a list or tuple to a function as separate positional arguments using *:

def multiply(a, b, c):
    print(a * b * c)
numbers = [2, 3, 4]
multiply(*numbers)   # same as multiply(2, 3, 4)

*numbers unpacks the list into separate arguments.

Unpacking a dictionary into keyword arguments

You can pass a dictionary to a function as separate keyword arguments using **:

def greet_person(name, greeting, punctuation):
    print(greeting, name + punctuation)
data = {
    "name": "Alice",
    "greeting": "Hi",
    "punctuation": "!"
}
greet_person(**data)   # same as greet_person(name="Alice", greeting="Hi", punctuation="!")

Here, the dictionary keys must match the parameter names.

Common Beginner Mistakes with Parameters and Arguments

1. Wrong number of arguments

Providing too many or too few arguments:

def f(x, y):
    print(x, y)
# f(10)        # ❌ missing 'y'
# f(10, 20, 30) # ❌ too many arguments

2. Mixing up positions

Assuming order doesn’t matter with positional arguments:

def login(username, password):
    print("Username:", username)
    print("Password:", password)
login("mypassword", "me")  # order swapped, likely wrong

Use keyword arguments to avoid this:

login(username="me", password="mypassword")

3. Using mutable default values (advanced warning)

Avoid using mutable objects like lists or dictionaries as default values; they can behave in surprising ways. For beginners, a safe rule:

def add_item(item, collection=None):
    if collection is None:
        collection = []
    collection.append(item)
    return collection

You don’t need to fully understand why yet, just remember this pattern when you need a “default list” or similar.

Practice Ideas

Try writing functions with different kinds of parameters:

  1. A function area_of_rectangle(width, height) that takes two positional arguments.
  2. A function greet_user(name, greeting="Hello") using a default parameter.
  3. A function average(*numbers) that computes the average of any number of values.
  4. A function show_profile(name, **details) that prints the user’s name and any extra information (age, city, hobby, etc.) given as keyword arguments.

Parameters and arguments are the main way to control what your functions do. With them, you can write a function once and use it in many different situations by passing different values.

Views: 15

Comments

Please login to add a comment.

Don't have an account? Register now!