Default Arguments in Python

In the previous article we saw the internal logic of Python functions and how they work. Now we will take a look at the Default Arguments in Python. Default arguments exist when the functions do not require values to be passed to them or the function accepts certain values even in the absence of user-given information. Let us look at an illustrative example scenario:

def printDetails(id, name="NA", price = "NA"):
     print(f "Id is {id}")
     print(f "Name is  {names}")
     print(f "Price is {price}")

printDetails(101, "abc", 100)
print()
printDetails(102)
print
printDetails(103, "xyz")
Output:
 Id is 101
 Name is  abc
 Price is 100

 Id is 102
 Name is  NA
 Price is NA
 Id is 103
 Name is  xyz
 Price is NA

Hence the program works with both the default value and then the subsequently modified value passed to the function.

Working with Default Arguments in Python

In Python, a non-default argument cannot follow a default argument.

def printDetails(id, name="NA", price):
     print(f" Id is {id}")
     print(f" Name is  {name}")
     print(f" Price is {price}")

printDetails(101, "abc", 100)
print()
printDetails(102)
print
printDetails(103, "xyz")
Output:
  File "main.py", line 1
    def printDetails(id, name="NA", price):
                     ^
SyntaxError: non-default argument follows default argument

The program produces this kind of error statement in such a scenario. Let us see a program where we use default and keyword arguments. In keyword arguments, we do not need to specify or follow a specific order.

def printDetails(id, name="NA", price="NA"):
     print(f" Id is {id}")
     print(f" Name is  {name}")
     print(f" Price is {price}")

printDetails(name="abc", id=100)
print()
printDetails(price=200, id=102)
print
printDetails(id=103)
Output:
 Id is 100
 Name is  abc
 Price is NA

 Id is 102
 Name is  NA
 Price is 200
 Id is 103
 Name is  NA
 Price is NA

Here, in the above program, the argument values can be provided in any order as they are keyword arguments.

Hence we have seen the usage of default arguments, in the next article we will delve further into Keyword Arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *