Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks

Friday, 9 December 2016

Python Function : Keyword Arguments, Defaults and Optional Arguments

Python function keyword and optional arguments - In the last article on Python functions, we have learned about basics of Python functions. The key takeaways from that article are as listed below:

  • Function is a sequence of statements grouped together, intended to be re-used in the program.
  • Functions are used to avoid repetition of the code in your program. Functions reduces redundancy and improves re-usability. Once you define a function, it can be used any number of times in the entire program, or even in other programs (we are yet to see 'Modules', where we can learn more about it).
  • We need the def keyword to create a function. It creates an object of function type and assigns a name to it, at the runtime. The syntax for defining a function is as below:

  • def function_name():
        # Block of code starts
        # Block of code ends

  • When we need to pass some information to a function, we need to use 'parameters' in the function definition. While calling the function, we provide information to the function through 'arguments'.
  • A function, after performing some operations, gives control back to the caller. While doing so, a function might return a value (or rather 'an object') to the caller using return statement. A function without any return value returns None to the caller.
In this article, we are going to learn more about Function Arguments in more details. To begin with, lets start our discussion be revisiting basics of function arguments.

Function Arguments

With function arguments, we can pass some information to a function. In order to store these arguments, function uses names in the function definition, called as Parameters. These parameters are the variables in the local scope of that function, to which values of passed in objects (through arguments) are assigned. When we pass the arguments in a function call, the sequence in which objects are passed matters a lot. The objects in the argument are assigned to the parameters from left to right. Also, the number of arguments being passed must be equal to number of parameters in the function definition. Lets verify this with some examples.

>>> def myFunction(x, y):
...     print "Value of 'x' = " + str(x)
...     print "Value of 'y' = " + str(y)

>>> myFunction(20, 30)
Value of 'x' = 20
Value of 'y' = 30

>>> myFunction(30, 20)
Value of 'x' = 30
Value of 'y' = 20

In above example, we have created a function myFunction which can accept two arguments, which then will be assigned to variables x and y. In order to verify whether the assignment will be from left to right or otherwise, we print the values of x and y. In our first function call myFunction(20,30), x (which is the first parameter) is assigned with the value 20 (which is the first argument) and y is assigned with the value 30. In our second function call, we swap the order of the arguments and observe that, those are matched to the parameters from left to right. So, you can't just randomly pass arguments in a function call, the order they are passed in matters a lot. This is the normal way of passing arguments. With Keyword arguments, we can specify which parameter must be assigned which value, in the function call itself, without bothering about the order, which we see next.

Keyword Arguments

While making a function call, you can mention the parameter name and assign a value to it, with param_name=value syntax, to explicitly instruct the function about the variable assignments. In this case, the arguments can be passed in any order.

>>> def myFunction(a, b, c):
...     print "Value of 'a' = " + str(a)
...     print "Value of 'b' = " + str(b)
...     print "Value of 'c' = " + str(c)

>>> myFunction(b=20, c=50, a=10)
Value of 'a' = 10
Value of 'b' = 20
Value of 'c' = 50

>>> myFunction(c=20, a=50, b=10)
Value of 'a' = 50
Value of 'b' = 10
Value of 'c' = 20

In above examples, we have assigned values to the function parameters in the function call itself. What would have happened, had we passed only two arguments, instead of three?

>>> myFunction(b=20, c=50)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: myFunction() takes exactly 3 arguments (2 given)

It throws in exception, saying that 'you have provided only 2 arguments when I expect 3 from you'. But what if we want to provide only two arguments or even one, expecting that the function should display None if a value is absent? This leads us to discuss on Defaults or Optional arguments.

Optional Arguments

With defaults, we can assign a default value to a function parameter. While making a function call, if the argument is not provided, the parameter takes the default value assigned to it. This not only avoids an exception, but makes the argument optional. When the values are specified, default values will be overwritten and parameters will be assigned with the values provided in the argument.

# Function with two optional arguments
>>> def welcome(name='User', country='India'):
...     print 'Hello ' + name + '! Welcome to ' + country + '.'

# We specify no argument, default arguments will be taken
>>> welcome()
Hello User! Welcome to India.

# We do not mention 'country' here, default value will be taken
>>> welcome(name='Mandar')
Hello Mandar! Welcome to India.

# We overwrite both the default values, using keyword arguments
>>> welcome(name='Mandar', country='America')
Hello Mandar! Welcome to America.

# With non-keyword arguments - order is crucial
>>> welcome('Mandar', 'Russia')
Hello Mandar! Welcome to Russia.

# We specify the name in a variable
>>> name = 'Mandar'
>>> welcome(name, 'Australia')
Hello Mandar! Welcome to Australia.

In above example, we created a function welcome() that takes two arguments name and country. We assign both these variables with default values 'User' and 'India' respectively, making both of these arguments optional. If we do not specify any of the argument, it's default value will be printed. If we specify it, the default values are overwritten with the values specified. Please observe the default value 'User' getting overwritten with the value 'Mandar' and the value 'India' with 'America'.

Putting it together

Having learned Keyword arguments and defaults, we create a list of items which we need to purchase from market. We consider items 'tomato' and 'onion' as mandatory ones and 'pizza' and 'burger' as optional arguments. So, our function accepts at least two and at most four arguments and prints the list of items & their quantities we should buy from market.

>>> def itemList(tomato, onion, pizza=0, burger=0):
...     print 'Tomato : ' + str(tomato)
...     print 'Onion : ' + str(onion)
...     print 'Pizza : ' + str(pizza)
...     print 'Burger : ' + str(burger)

>>> itemList(2,4)
Tomato : 2
Onion : 4
Pizza : 0
Burger : 0

>>> itemList(2,4,1)
Tomato : 2
Onion : 4
Pizza : 1
Burger : 0

>>> itemList(2,4,burger=1)
Tomato : 2
Onion : 4
Pizza : 0
Burger : 1

>>> itemList(2,4,1,5)
Tomato : 2
Onion : 4
Pizza : 1
Burger : 5

>>> itemList(onion=2,tomato=3)
Tomato : 3
Onion : 2
Pizza : 0
Burger : 0

With this we close our discussion on passing arguments to functions. We started with normal way of passing arguments to a function, in which order of arguments plays the critical role. We then discussed on keyword arguments, with which we can pass arguments with parameters assigned with values, irrespective of the order they appear in the function definition. We then discussed about defaults, which help us create optional arguments. We aren't yet done with arguments though, as we are yet to discuss on variable length arguments to a function. We see them in the next article. Please share your views and opinions in the comments section below and stay connected. Thank you.


Post a Comment