Arguments

What are Arguments

In Python, arguments are the values that are passed to a function when it is invoked or called. They are essential as they allow a function to receive data it can use in executing its instructions. You can send any data types such as a list, string, number, etc., as an argument to a function.

To better visualize this concept, let’s write a simple function that multiplies two numbers, with those numbers being the arguments.

1def multiply(a, b):  # a and b are the arguments
2    return a * b
3
4print(multiply(2, 3))  # Prints: 6

In the above example, the function multiply is called with the arguments 2 and 3, and it returns the multiplied result 6.

Positional Arguments

Positional arguments are the most common type and must be passed in the order in which they’re defined in the function.

1def greet(name, age):  
2    print(f"Hello {name}, you are {age} years old.")
3
4greet("John", 22)   # Prints: Hello John, you are 22 years old.

In the example above, “John” and 22 are positional arguments. They need to be in the same order as the parameters name and age declared in the function greet.

Caution

Mismatching the order of arguments with their respective function parameters can lead to logical error, or unexpected behavior of the function.

Keyword Arguments

Keyword arguments allow you to specify arguments by their names, overriding the order. They are identified by the function parameter’s name followed by an equal sign and the value you want to set.

1def greet(name, age):  
2    print(f"Hello {name}, you are {age} years old.")
3
4greet(age=22, name="John")   # Prints: Hello John, you are 22 years old.

Here, even though “John” and 22 are not in the order of parameters in function, Python knows which is which because they’re defined by keywords.

Note

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

Arbitrary Arguments

Sometimes, you may not know beforehand how many arguments you will pass to a function. Python allows for this with arbitrary arguments or varargs. To denote this, an asterisk (*) is used before the parameter name in the function definition.

1def greet(*names):  
2    for name in names:
3        print(f"Hello {name}.")
4
5greet("John", "Maria", "Kate")   
6# Prints: 
7# Hello John.
8# Hello Maria.
9# Hello Kate.

In this example, Python packs all of the arguments into a tuple that can be iterated over, which is what happening in the for loop.

Functions are a powerful tool in Python, and understanding how arguments work is integral to leveraging this power efficiently and effectively.