Keyword and Positional Argument in Python
In Python, functions can accept values in different ways when we call them. When calling a function, the way you pass values decides how they will be received by the function. The two most common ways are:
- Keyword arguments
- Positional arguments
Both methods are useful, but they behave differently.
Keyword Argument
Keyword arguments mean you pass values by parameter names while calling the function.
- The order does not matter as long as the names are correct.
- Defaults are used if some arguments are not provided.
- This makes the code more readable and less error-prone.
Example: The following example shows how keyword arguments work and why order doesn’t matter.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
nameAge(name="Prince", age=20)
nameAge(age=20, name="Prince")
Output
Hi, I am Prince My age is 20 Hi, I am Prince My age is 20
Explanation:
- In first call, name="Prince" and age=20 are passed in order.
- In second call, order is swapped but the result is the same since parameters are matched by name.
Benefits of Keyword Arguments
- More clarity in code (easy to understand what each value means).
- No dependency on the order of values.
- Helpful when functions have many parameters.
Positional Arguments
Positional arguments mean values are passed in the same order as parameters are defined in the function.
- The first value goes to the first parameter, second to the second and so on.
- Changing the order can lead to unexpected results.
Example 1: This example show how positional arguments work and what happens if you mix up the order.
def add(a, b):
return a + b
# 5 goes to a, 10 goes to b
print(add(5, 10))
Output
15
Explanation: Arguments are passed by their position.
Example 2: This example shows how changing the order of positional arguments can completely change the result of a mathematical operation.
def minus(a, b):
return a - b
a, b = 20, 10
result1 = minus(a, b)
print("Correct order:", result1)
# Swapping values changes meaning
result2 = minus(b, a)
print("Swapped order:", result2)
Output
Correct order: 10 Swapped order: -10
Explanation:
- In first call, 20 - 10 = 10 -> correct.
- In second call, arguments are swapped (10 - 20 = -10) -> unexpected result.
- This shows how positional arguments strictly depend on order.
Note: Use positional arguments only when you are sure about the correct order of parameters. Otherwise, prefer keyword arguments to avoid mistakes.
Keyword vs Positional Argument
Here’s a simple comparison to summarize everything:
| Keyword Arguments | Positional Arguments |
|---|---|
| Parameter names are used to pass values. | Values are passed strictly in the defined order. |
| Order of values does not matter. | Order of values must be correct. |
| More readable and less error-prone. | Easier for short functions with few arguments. |
| Example: func(a=10, b=20) | Example: func(10, 20) |