5.3 Parameters and Arguments in a function (BT101CO)

In Python, Parameters and Arguments are the mechanisms used to pass data into a function. While these terms are often used interchangeably, they represent two different stages of a function's life cycle.

1. Parameters vs. Arguments

  • Parameters: These are the variables listed in the function's definition. They act as placeholders for the data the function expects to receive.
  • Arguments: These are the actual values passed to the function when it is called.

Example:

def greet(name):      # 'name' is a parameter
    print(f"Hello, {name}!")

greet("Ashok")        # "Ashok" is an argument

2. Types of Arguments

Python provides several flexible ways to pass arguments into a function:

A. Positional Arguments

The most common type. Arguments are assigned to parameters based on their order (position).

def display_info(name, age):
    print(f"Name: {name}, Age: {age}")

display_info("Amit", 25) # "Amit" goes to name, 25 goes to age

B. Keyword Arguments

You can specify the parameter name during the function call. This allows you to ignore the order of arguments, making the code more readable.

display_info(age=30, name="Suman") # Order doesn't matter here

C. Default Arguments

You can provide a default value to a parameter in the function definition. If the caller doesn't provide an argument, the default value is used.

def greet(name, message="Welcome"):
    print(f"{message}, {name}!")

greet("Ashok")            # Output: Welcome, Ashok!
greet("Ashok", "Hi")      # Output: Hi, Ashok!
Note: Default parameters must always follow non-default parameters.

3. Variable-Length Arguments (*args and **kwargs)

Sometimes you don't know in advance how many arguments will be passed. These are handled using the * (asterisk) and ** (double asterisk) symbols.

A. *args (Non-Keyword)

Allows a function to accept any number of positional arguments. Inside the function, these are stored in a Tuple.

def sum_all(*numbers):
    total = 0
    for num in numbers:
        total += num
    return total

print(sum_all(10, 20))         # Output: 30
print(sum_all(1, 2, 3, 4, 5))  # Output: 15

B. **kwargs (Keyword)

Allows a function to accept any number of keyword (named) arguments. Inside the function, these are stored in a Dictionary.

def show_profile(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

show_profile(Name="Ashok", Age=25, City="Lalitpur")

4. Pass by Object Reference

Python uses Pass by Object Reference to handle data internally:

  1. Mutable Objects (e.g., List, Dict): If you modify it inside the function, the change will reflect outside the function.
  2. Immutable Objects (e.g., Integer, String): The function cannot change the original value; it creates a local copy if modified.

Example with a List (Mutable):

def add_item(my_list):
    my_list.append(4)

nums = [1, 2, 3]
add_item(nums)
print(nums) # Output: [1, 2, 3, 4]

5. Unpacking Operators (* and **)

You can use these symbols in reverse to "unpack" a collection into a function call.

  • Unpacking a List/Tuple: Use * to spread elements into positional arguments.
  • Unpacking a Dictionary: Use ** to spread key-value pairs into keyword arguments.
def add(a, b, c):
    return a + b + c

nums = [1, 2, 3]
print(add(*nums)) # Equivalent to add(1, 2, 3)

Summary Checklist

Type Data Structure When to Use?
PositionalOrder-basedFor simple, few-parameter functions.
KeywordName-basedFor functions with many parameters.
DefaultPre-set valuesFor optional settings.
*args**Tuple**When handling unknown number of items.
**kwargs**Dictionary**When handling unknown named settings.

Practice Quiz