Python optional arguments in function [Practical Examples]


Written By - Bashir Alam

 

Advertisement

Introduction to Python optional arguments

An argument is a value that is passed to the function when it is called. Sometimes, we need to have optional arguments as well, which means even if we will not pass the values, the program shouldn't return any error. In this tutorial, we will learn about Python optional arguments. We will discuss how we can pass Python optional arguments to the methods using various ways. We will cover default arguments, keyword arguments, and keyword arguments using different examples.

At the same time, we will also learn about how we can use **kwargs to have python optional arguments. Furthermore, we will also cover the Python optional argument errors as well. In a nutshell, this tutorial will contain all the necessary details and information that you need to know in order to start working with python optional arguments.

 

Getting started with Python optional arguments

An argument is simply a value provided to a function when you call it. And we already discussed that the Python optional argument is an argument with a default value. We can specify a default value for an argument using the assignment operator. But first let us take an example of Python argument and see how it works. See the example below:

# python function
def main(num):
    # return value of function
    return num*num
# calling function with argument
print(main(10))

Output:

100

Notice that the main function takes 10 as an argument and if we will not pass this argument, we will get an error. See the example below:

# python function
def main(num):
    # return value of function
    return num*num
# calling function without argument
print(main())

Output:

Python optional arguments

Notice that when we called the function without the argument, we got an error, because the argument was not an optional argument. In the case of an optional argument, the program will not return any error even if we will not pass the argument.

 

Using Python optional arguments with default arguments

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value. The simple syntax of the Python default argument looks like this:
def main(keywordname = Value_assigned):
    # function's statements

Notice that while defining a function, we passed the parameter and the value together so that if the user will not provide the argument, the function will not return any error.

Advertisement

 

Examples of Python Default argument

Now let us take an example and see how we can use the default argument as an optional argument in Python. See the example below where we have used one default argument as an optional argument.

# Python optional arguments with default argument
def main(num1, num2, num3 = 0):
    # return the sum of the arguments
    return num1+num2 +num3
# calling the function with two arguments
print("the sum is: " ,main(10,5))

Output:

the sum is: 15

Notice that the function was supposed to take three arguments but the third argument was optional because of its default value, we were able to get the returned value after passing two arguments. If we will provide all three arguments, then the default value of the third argument will be replaced by the new value. See the example below:

# Python optional arguments with default argument
def main(num1, num2, num3 = 0):
    # return the sum of the arguments
    return num1+num2 +num3
# calling the function with
print("the sum is: " ,main(10,5, 5))

Output:

the sum is: 20

Notice that the default value of the argument was replaced by the new and updated value. Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values which means non-default arguments cannot follow default arguments. For example, a non-default argument cannot be on the left side of the default one. See the Python code below:

# Python optional arguments with default argument
def main(num1=0, num2, num3):
    # return the sum of the arguments
    return num1+num2 +num3
# calling the function with
print("the sum is: " ,main(10,5, 5))

Output:

Optional argument

Notice that we get an error that says a non-default argument follows the default one.

 

Using Python optional arguments with keyword arguments

Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator. While calling the function with keyword arguments, the order of the arguments does not matter, we can call them in any order, but based on the keyword they will be assigned. The following is the simple syntax of Python keyword arguments.

Advertisement
def function(keyword1 = value1, keyword2 = vlaue2):
    # function's statements

Notice that the keywords are assigned the values.

 

Examples of keyword arguments

Now let us see how we can use the keyword arguments in Python. See the following example below, which show how we can use the keyword arguments in the Python programming language.

# Python optional arguments with default argument
def main(num1 =0, num2 = 0, num3 = 0):
    # printing the arguments
    print("first argument is: ", num1)
    print("second argument is: ", num2)
    print("third argument is: ", num3)
# calling the function 
main(num2=10,num3=7, num1=5)

Output:

first argument is: 5
second argument is: 10
third argument is: 7

Notice that although the order of the arguments while calling was not in order still they were assigned to the specified parameters because of the keywords. One advantage of using keyword arguments is that even if we will not call any of the arguments, the program will still run. For example, see the  python program below:

# Python optional arguments with default argument
def main(num1 =0, num2 = 0, num3 = 0):
    # printing the arguments
    print("first argument is: ", num1)
    print("second argument is: ", num2)
    print("third argument is: ", num3)
# calling the function without any arguments
main()

Output:

first argument is: 0
second argument is: 0
third argument is: 0

Notice that we call the function without any arguments but still did not get any error, which means the keyword arguments can be used as python optional arguments as well.

Advertisement

 

Using Python optional arguments with arbitrary arguments

An arbitrary argument list is a Python feature to call a function with an arbitrary number of arguments. It's based on the asterisk “unpacking” operator *. The following is the simple syntax of Python arbitrary arguments.

def main(*arg):
    # for loop to iterate through the arguments

The passed arguments will be in the form of a list so we need to iterate through them to get access to each of the provided arguments.

 

Examples of the Python arbitrary arguments

Now let us take an example and see how we can use the python arbitrary arguments in our program. See the Python program below:

# python function
def main(*num):
    count = 0
    # for loop
    for i in num:
        count += i
    # return value 
    return count
# calling function
print(main(10, 5, 5, 4))

Output:

24

Notice that we can pass as many arguments as we want, the program will not return any error. Even if we will not provide any argument, still the program is going to run without any error. See the example below:

# python function
def main(*num):
    count = 0
    # for loop
    for i in num:
        count += i
    # return value 
    return count
# calling function
print(main())

Output:

0

Notice that we didn't provide any of the arguments, still the program run without any error.

 

Using Python optional arguments using **kwargs

**kwargs is a dictionary of keyword arguments. The ** allows us to pass any number of keyword arguments. The main difference between single asterisk *args and double **kwargs is that the *args contain non-keyword arguments while **kwargs contains keyword arguments. You can read more about the differences between **kwargs and *args from the article on Python **kwargs and *args.

 

Example of Python **kwargs

Now let us take an example and see how we can use the double-asterisk to pass any number of keyword arguments to the function. See the example below:

# python method
def main(**student_data):
    # printing the details
    print("\nStudent details:")
    # for loop to iterate
    for key, value in student_data.items():
        print("{} is {}".format(key,value))
# calling the function
main(Name = "Bashir", age = 21, university = 'UCA')
main(Name = "Rt", age= 20, email = "alam23@gmail.com;")

Output:

Advertisement
Student details:
Name is Bashir
age is 21
university is UCA

Student details:
Name is Rt
age is 20
email is alam23@gmail.com;

Notice that in the first we passed the university name while in the second we passed email, instead of the university and the program works. We can pass as many arguments as we want using the above method.

 

Summary

A Python optional argument is an argument with a default value. We can specify a default value for an argument using the assignment operator. There is no need to specify a value for an optional argument when we call a function. In this tutorial, we learned about Python optional arguments. We learn how we can use different methods to pass optional arguments by taking examples.

We covered four different ways through which we can pass Python optional arguments. We also covered the errors that might occur while passing arguments to the function. In a nutshell, this tutorial contains all the necessary methods and examples that you can use to generate Python optional arguments.

 

Further Reading

Python methods
Python program control
Ptyhon **kwargs and *args

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment