Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using Keyword Arguments

Example 7.6. Using Keyword Arguments

#!/usr/bin/python
# Filename: func_key.py def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c

func(3, 7)
func(25, c=24)
func(c=50, a=100)

Output

$ python func_key.py
a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50

How It Works

The function namedfunc has one parameter without default argument values, followed by two parameters with default argument values.

 

In the first usage,func(3, 7), the parametera gets the value3, the parameterb gets the value5 and c gets the default value of10.

In the second usage func(25, c=24), the variablea gets the value of 25 due to the position of the argument. Then, the parameterc gets the value of24 due to naming i.e. keyword arguments. The variableb gets the default value of5.

In the third usage func(c=50, a=100), we use keyword arguments completely to specify the values. Notice, that we are specifying value for parameterc before that fora even thougha is defined beforec in the function definition.