Default Arguments and Positional arguments in Python  

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.

Please click Like if you loved this article?

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:

See also
String startswith() and endswith()
fname mname lname
1st example Mary Elizabeth Smith
2nd example Elizabeth Mary Smith

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

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

Please click Like if you loved this article?

Ads Blocker Image Powered by Code Help Pro
Ads Blocker Detected!!!

This website does not work properly with AdBlock. We have detected that you are using extensions to block ads. Please disable Adblocker to view the content.

Refresh