Function Arguments

Default Argument Values

For some functions, you may want to make some parameters optional and use default values in case the user does not provide values for them. This is done with the help of default argument. Youcan specify a arguement as default arguement by assigning a value using (=) operator.

def say(message, times=1):
    print(message * times)

say('Hello ')
say('Hello ', 5)

Output

Hello 
Hello Hello Hello Hello Hello

How It Works

Here we used a function named say for repeating what the user say .In this function we pass two parameters named as message and times.

The message parameter takes the value that a user wants to repeat and times takes how many times user wants to repeat the message.

If the user don’t supply a value to the times parameter, then by default, the string is printed just once. We achieve this by specifying a default value of 1 to the parameter times.

Keyword Arguments

If you have some functions with many parameters and you want to specify values only to some of them, then you can give values for such parameters by naming them - this is called keyword arguments - we use the name (keyword) instead of the position to specify the arguments to the function.(keyword basically the name used in the function declaration)

There are two advantages

  1. First, using the function is easier since we do not need to worry about the order of the arguments.
  2. Second, we can give values to only those parameters to which we want to, provided that the other parameters have default argument values.
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

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 named func has one parameter without a default argument value, followed by two parameters with default argument values.

  1. In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the value 7 and c gets the default value of 10.

  2. In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the argument. Then, the parameter c gets the value of 24 due to keyword arguments. The variable b gets the default value of 5.

  3. In the third usage func(c=50, a=100), we use keyword arguments for all specified values. Notice that we are specifying the value for parameter c before the value of a. But it doest not matter when we specifying the keyword arguements.