Skip to main content

Functions

Positional and Keyword Arguments

 

Positional Arguments:

Positional arguments are the most common type of arguments in Python. They are passed to a function in the same order as they are defined in the function's parameter list.

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

# Calling the function with positional arguments
greet("Alice", 30)

 

Keyword Arguments:

Keyword arguments are passed to a function with a specific keyword identifier. They do not rely on the order of parameters defined in the function.

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

# Calling the function with keyword arguments
greet(age=25, name="Bob")

 

Default Values:

You can also provide default values for function parameters, which allows the function to be called with fewer arguments.

def greet(name="Anonymous", age=18):
    print(f"Hello, {name}! You are {age} years old.")

# Calling the function with default values
greet()

 

Mixing Positional and Keyword Arguments:

You can mix positional and keyword arguments in a function call, but positional arguments must come before keyword arguments.

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

# Mixing positional and keyword arguments
greet("Charlie", age=35)

 

Understanding these concepts will help you effectively pass arguments to functions in Python, providing flexibility and clarity in your code.