Python Function Arguments & Parameters

Parameters are variables listed in a function definition, while arguments are values passed to a function when it is called.

Types of Function Arguments

1. Positional Arguments

Arguments are assigned to function parameters in the order they are passed.

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25)

Try It Now

2. Keyword Arguments

Arguments are passed using parameter names, making the order irrelevant.

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet(age=25, name="Alice")

Try It Now

3. Default Arguments

Parameters can have default values, which are used if no argument is provided.

def greet(name="Guest"):
    print(f"Hello {name}!")

greet()
greet("Alice")

Try It Now

4. Variable-Length Arguments (*args)

The *args syntax allows passing multiple arguments as a tuple.

def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3, 4))

Try It Now

5. Keyword Variable-Length Arguments (**kwargs)

The **kwargs syntax allows passing multiple keyword arguments as a dictionary.

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

display_info(name="Alice", age=25, city="New York")

Try It Now

Key Takeaways

  • Use positional arguments for simple cases.
  • Use keyword arguments for better readability.
  • Use *args and **kwargs for flexible argument passing.