KAHIBARO Bookshelves
Discord Login Register

9.3. 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:

  • Parameters are the names listed in a function’s definition.
  • Arguments are the actual values you pass when you call the function.

Think of a function like a machine:

  • Parameters = labeled input slots on the machine.
  • Arguments = the actual items you put into those slots.
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
  • First argument → first parameter (a)
  • Second argument → second parameter (b)

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:

  • animal gets "dog" or "cat"
  • name gets "Rex" or "Mittens"

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:

  • Positional arguments must come first.
  • Keyword arguments come after.
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
  • If greeting is not given, it uses "Hello".
  • If an argument is given for greeting, that value is used instead.

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:

  • greeting gets the first argument.
  • All remaining arguments go into names.

`**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:

  • options is a dictionary like {"volume": 10, "brightness": 70, "theme": "dark"}.

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:

  • a = 1
  • b = 2
  • args = (3, 4)
  • kwargs = {'x': 10, 'y': 20}

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:

  • Use None as a default, then create the list/dict inside the function.
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: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms