Course
Default Arguments
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
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
# Function definition is heredef printinfo( name, age = 35 ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return
# Now you can call printinfo functionprintinfo( age=50, name="miki" )printinfo( name="miki" )
It will produce the following output
Name: mikiAge 50Name: mikiAge 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 = 60maths = 70result = 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 = 40maths = 46result = percent(phy,maths, 100)
Example
Here is the complete example
def percent(phy, maths, maxmarks=200): val = (phy+maths)*100/maxmarks return val
phy = 60maths = 70result = percent(phy,maths)print ("percentage:", result)
phy = 40maths = 46result = percent(phy,maths, 100)print ("percentage:", result)
It will produce the following output
percentage: 65.0percentage: 86.0
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.