Examples of how to pass optional arguments in a python function?
Basic python function
Let's start by creating a simple function in python:
def function_test(a,b):print(a,b)return Nonemyfunc(1,2)
gives
1 2
However if we try to pass a third variable
myfunc(1,2,7)
will generate an error message
too many values to unpack (expected 2)def myfunc(a,b):print('function print', a,b)return a, b, a+boutput = myfunc(1,2)print(output[0])print(output[1])print(output[2])
gives
1 2123
Passing optional arguments with *args
def myfunc(a,b, *args):output = a + bfor ar in args:print('Optional argument:', ar)output += arreturn outputmyfunc(1,2,7)
gives
Optional argument: 710
Another example
def myfunc(a,b, *args):output = a + bfor ar in args:print('Optional argument:', ar)output += arreturn outputmyfunc(1,2,7,10,20)
gives
Optional argument: 7Optional argument: 10Optional argument: 2040
Pass a list
def myfunc(a,b, *args):output = a + bfor ar in args:print('Optional argument:', ar)return outputl = [7,10,20]myfunc(1,2,l)
gives
Optional argument: [7, 10, 20]
Pass a dictionary
def myfunc(a,b, *args):output = a + bfor ar in args:print('Optional argument:', ar)return outputd = {'bob':42, 'emma':47}myfunc(1,2,d)
gives
Optional argument: {'bob': 42, 'emma': 47}
Passing optional arguments with **kwargs
Another possibility is to use **kwargs to name optional variables directly:
def myfunc(a,b, **kwargs):print('kwargs: ', kwargs)return Nonemyfunc(1,2,lang='fr')
gives
{'lang': 'fr'}
In the function to test if there is an optional argument like 'lang' we can use:
if 'lang' in kwargs:
to get the value of the 'lang' variable:
kwargs['lang']
Example
def myfunc(a,b, **kwargs):print(kwargs)if 'lang' in kwargs:print("found it")print( kwargs['lang'] )return a + bmyfunc(1,2,lang='fr', )
gives
{'lang': 'fr'}found itfr
Global variable
In python we can also define global variables
global cc = 123def myfunc(a,b):print(c)return a + bmyfunc(1,2)
gives
123
