In Python, positional arguments and default arguments are used when passing values to a function.
1. Positional arguments
A positional argument is passed according to the position (order) of the parameter.
def student(name, age):
print(name)
print(age)
student("Sajin", 20)
Output :
Sajin
20
Step-by-step
Parameter Argument
name "Sajin"
age 20
Python matches values based on their order.
If you change the order:
student(20, "Sajin")
Output:
20
Sajin
Here, name = 20 and age = "Sajin".
2. Default arguments
A default argument has a value assigned in the function definition.
If you don't pass a value, Python uses the default.
def login(username="admin", password="1234"):
print(username, password)
login()
Output:
admin 1234
You can also pass your own values:
login("Sajin", "5678")
Output:
Sajin 5678
Step-by-Step:
def login(username="admin", password="1234"):
print(username, password)
login("Sajin")
Output:
Sajin 1234
- "Sajin" replaces the default username.
- Password is not provided.
- So Python uses the default password "1234".
3. Positional + Default arguments
def login(username, password="1234"):
print(username, password)
login("Sajin")
Output:
Sajin 1234
Here:
- username is a required positional parameter.
- password is a default parameter.
You can also provide both:
login("Joe", "5678")
Output:
Joe 5678
Important rule: A parameter without a default value cannot come after a parameter with a default value.
❌ Incorrect:
def login(username="admin", password):
print(username, password)
✅ Correct:
def login(username, password="1234"):
print(username, password)
Top comments (0)