Home » Python Tutorial » Default Arguments and Positional arguments in Python

Default Arguments and Positional arguments in Python


Reading Time - 3 mins

In the functions tutorial, we have seen how to pass arguments to the functions. Default Arguments and Positional arguments in Python are the different ways we can pass arguments to the function.

Default arguments in Python:

Using assignment operator =, we can assign a default value to an argument.

def my_function(fname,lname='Smith'): 
  print("Hello "+fname+' '+lname)

my_function("Mary")
my_function("Mary","James")

The function is accepting two parameters fname and lname. And we are assigning a default value to lname. Since the function accepts 2 parameters we should pass 2 values while calling the function. But in the above example, while calling the function for the first time, we passed only one value and the code executed without any errors. That’s because we are passing the default value to the other argument.

While using the default argument, the default value will be assigned if we don’t pass any value to the default argument. When calling the function for the second time, we are passing the value to the argument lname, and the value passed will override the default value.

We can have any number of default arguments.

def my_function(fname,mname='Elizabeth',lname='Smith'): 
  print("Hello "+fname+' '+mname+' '+lname)

my_function("Mary")

Positional arguments in Python:

Let’s say a function accepts 3 parameters “fname, mname and lname“. We are passing 3 values while calling the function.

def my_function(fname,mname,lname): 
  print("Hello "+fname+' '+mname+' '+lname)

my_function("Mary","Elizabeth","Smith")
my_function("Elizabeth","Mary","James")

The mapping between the value passed and the function arguments are:

fnamemnamelname
1st exampleMaryElizabethSmith
2nd exampleElizabethMarySmith

In positional arguments, the value passed will be mapped to the function arguments based only on the order in which the values are passed.

READ  Python Dictionary

We discussed Default Arguments and Positional arguments in Python. If interested please check here for more information on positional arguments.

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions