Notes
Categories

Positional Arguments and Keyword Arguments in Python [ English ]

< Prev Next >

1. Introduction

When calling a function in Python, arguments can be supplied in different ways. The two most common and fundamental methods are:

Understanding these forms is essential for writing correct and readable function calls.


2. Positional Arguments

2.1 Definition

Positional arguments are passed to a function in the same order as the parameters are defined. Each value is assigned to a parameter according to its position.


2.2 Example

def display(name, age):
    print("Name:", name)
    print("Age:", age)

display("Rahul", 20)

Output:

Name: Rahul
Age: 20

Here:


2.3 Important Rule

The order must be correct.

display(20, "Rahul")

Output:

Name: 20
Age: Rahul

This produces incorrect results because the arguments are swapped.


3. Keyword Arguments

3.1 Definition

Keyword arguments are passed by explicitly specifying the parameter name and its value. This removes the dependency on position.


3.2 Example

def display(name, age):
    print("Name:", name)
    print("Age:", age)

display(age=20, name="Rahul")

Output:

Name: Rahul
Age: 20

3.3 Advantages


4. Combining Positional and Keyword Arguments

You can use both in the same function call.

def student(name, age, city):
    print(name, age, city)

student("Rahul", age=20, city="Jaipur")

✔ Valid usage


4.1 Rule to Follow

Positional arguments must always come before keyword arguments.

✘ Invalid:

student(name="Rahul", 20, city="Jaipur")

This results in a syntax error.


5. Comparison

Feature Positional Arguments Keyword Arguments
Based on Position Parameter name
Order sensitivity Yes No
Readability Moderate High
Flexibility Less More

6. When to Use


7. Key Insight

Positional arguments are concise but can lead to errors if the order is incorrect. Keyword arguments enhance clarity and make code self-explanatory, especially in complex functions.


8. Conclusion

Both positional and keyword arguments are essential tools in Python. A good programmer knows when to use each appropriately to write clean, efficient, and maintainable code.

< Prev Next >