Python - Default Arguments



Python Default Arguments

Python allows to define a function with default value assigned to one or more formal arguments. Python uses the default value for such an argument if no value is passed to it. If any value is passed, the default value is overridden with the actual value passed.

Default arguments in Python are the function arguments that will be used if no arguments are passed to the function call.

Example of Default Arguments

# Function definition is here
def printinfo( name, age = 35 ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Age ", age)
   return

# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

It will produce the following output

Name: miki
Age 50
Name: miki
Age 35

In the above example, the second call to the function doesn't pass value to age argument, hence its default value 35 is used.

Let us look at another example that assigns default value to a function argument. The function percent() is defined as below −

def percent(phy, maths, maxmarks=200):
   val = (phy+maths)*100/maxmarks
   return val

Assuming that marks given for each subject are out of 100, the argument maxmarks is set to 200. Hence, we can omit the value of third argument while calling percent() function.

phy = 60
maths = 70
result = percent(phy,maths)

However, if maximum marks for each subject is not 100, then we need to put the third argument while calling the percent() function.

phy = 40
maths = 46
result = percent(phy,maths, 100)

Example: Calling Function Without Keyword Arguments

Here is the complete example −

def percent(phy, maths, maxmarks=200):
   val = (phy+maths)*100/maxmarks
   return val

phy = 60
maths = 70
result = percent(phy,maths)
print ("percentage:", result)

phy = 40
maths = 46
result = percent(phy,maths, 100)
print ("percentage:", result)

It will produce the following output

percentage: 65.0
percentage: 86.0
Advertisements