python : positional argument, default argument
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…
In Python, functions accept values through positional arguments and default arguments. Positional arguments are passed based on the order of parameters in the function definition. For example:
def student(name, age):
print(name)
print(age)
student("Sajin", 20)
The output will be:
Sajin
20
If the order of arguments is changed, it will cause an error as the values are matched based on their position.
def student(age, name):
print(name)
print(age)
student(20, "Sajin")
Output:
20
Sajin
In this case, age is assigned 20 and name is assigned Sajin, which is different from the previous example.
Default arguments in Python are defined within the function definition and have a value assigned to them. If no value is passed during the function call, Python uses the default value. For instance:
def login(username="admin", password="1234"):
print(username, password)
login()
The output will be:
admin 1234
This is because no arguments are provided, so Python uses the default values "admin" and "1234". However, if custom values are passed:
login("Sajin", "5678")
Output:
Sajin 5678
Here, "Sajin" replaces the default username, and "5678" replaces the default password. The default password remains "1234" if only the username is provided:
login("Sajin")
Output:
Sajin 1234
Positional arguments and default arguments can be combined in a single function definition. Positional arguments must come before default arguments. An incorrect function definition would be placing a default argument after a positional argument, which is not allowed:
def login(username="admin", age=20):
print(username, age)
This function definition is incorrect. The correct order is:
def login(username, age=20):
print(username, age)
This rule ensures that positional arguments are clearly defined before default arguments in the function definition.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.