. Advertisement .
..3..
. Advertisement .
..4..
Optional arguments are useful for defining functions that can be called with different sets of arguments. Optional arguments are defined using the ‘*’ symbol in the argument definition. In this blog, we will look at this function and how it can be used. Read on.
How To Use Optional Arguments In Python?
Utilize *args to create optional arguments in Python. In Python, you can make optional arguments by utilizing *args. So, without wasting any time, let’s take a look at the following example:
def myfunction(first_name, last_name, *args): print(first_name) print(last_name) for argument in args: print(argument) myfunction('aarti','patel',8,30,45)
Result:
aarti patel 8 30 45
In Python, utilize **kargs to create optional arguments. In Python, you can create optional arguments by utilizing **kargs. So, without wasting any more time, let’s take a look at the following example:
def myFunction(**kwargs): for key, value in kwargs.items(): print ("%s = %s" %(key, value)) myFunction(std='12', name='arti patel', subject='physics', marks='83')
Result:
std = 12 name = arti patel subject = physics marks = 83
Option 1: Utilize *args
In Python, you can make optional arguments by utilizing *args. So, without wasting any time, let’s take a look at the following example:
def myfunction(first_name, last_name, *args): print(first_name) print(last_name) for argument in args: print(argument) myfunction('aarti','patel',8,30,45)
Result:
aarti
patel
8
30
45
Option 2: Utilize **kargs
In Python, you can create optional arguments by utilizing **kargs. So, without wasting any more time, let’s take a look at the following example:
def myFunction(**kwargs): for key, value in kwargs.items(): print ("%s = %s" %(key, value)) myFunction(std='12', name='arti patel', subject='physics', marks='83')
Result:
std = 12
name = arti patel
subject = physics
marks = 83
Conclusion
We hope you found our article on using optional arguments in Python useful. We understand that dealing with this can be confusing, therefore we hope that our information has assisted you in resolving it. Please leave a comment if you have any further questions or concern. Thank you for taking the time to read; we are always delighted anytime one of our pieces can give important information on a topic like this!
Leave a comment