Function Arguments in Python. Topic 16

Functions-Arguments-In-Python.-Topic-21.webp

What is *args and **kwargs?

In Python programming *args and **kwargs are used in function definition.  *args and **kwargs are special types of parameters that allow to handle multiple arguments. These are especially useful when we need advanced flexibility in function arguments.

*args (Arbitrary Positional Arguments):

When using *args, you can pass any number of positional arguments to the function. This argument goes to the function in the form of tuples. So let’s try a program:

def sum_all(*args):
    result = 0
    for num in args:
        result += num
    return result

print(sum_all(1, 2, 3, 4))  

The Output Of This Code Will Be:

Output
Output: 10

Here, we pass the multiple values through the *args. and function handle this as a form of tuple. Let’s check if is it a tuple or not. Function Arguments in Python. Topic 21

def sum_all(*args):
    print(type(*args))

print(sum_all(1, 2, 3, 4))  

The Output Of This Code Will Be:

Output
Output : <class 'tuple'>

2. **kwargs (Arbitrary Keyword Arguments):

In Python programming, When we use **kwargs, we can pass any number of keyword arguments to a function. These arguments come inside the function in the form of a dictionary. Let’s see an example of how it works:

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Shivam", age=25, city="India")

The Output Of This Code Will Be:

Output
name: Shivam
age: 25    
city: India

Here, we pass the multiple keywords through the **kwargs, and the function handles these as a form of dictionary. Let’s check if it is a dictionary or not.

def print_info(**kwargs):
    print(type(kwargs))

print_info(name="Shivam", age=25, city="India")

The Output Of This Code Will Be:

Output
<class 'dict'>

Check another example where we pass the positional arguments and keyword arguments together.

def display_info(*args, **kwargs):
    print("Positional Arguments (*args):")
    for arg in args:
        print(arg)

    print("\nKeyword Arguments (**kwargs):")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Calling the function with both positional and keyword arguments
display_info(3, "Priti", city="India", age=21)

The Output Of This Code Will Be:

Output
Positional Arguments (*args):
3
Priti

Keyword Arguments (**kwargs):
city: India
age: 21

In this program, **args accept – 3 and “priti” in the form of tuples and **kwargs accept these – city=”India”, age=21 in the form of a dictionary.

You can also change the names of *args and **kwargs to something else. You can do like this *code **coder, but *args and **kwargs a conventions that are used in industry. You can use any name with * and ** symbols.

In summary, *args is used to handle arbitrary positional arguments, and **kwargs is used to handle arbitrary keyword arguments in Python. Both of these parameters make a function flexible and generic.

Example For Practice Class & Objects

Easy to Intermediate Questions:

  1. Sum Function: Write a Python function calculate_sum that takes any number of arguments and returns their sum.
  2. Display Info: Create a function display_info that takes a person’s name and age as positional arguments and any additional information as keyword arguments. Display the name, age, and any additional information received.
  3. Average Function: Define a function calculate_average that takes any number of numerical arguments and calculates their average.
  4. Shopping Cart: Implement a function add_to_cart that takes items as positional arguments and their quantities as keyword arguments. Display the items and their quantities in the shopping cart.
  5. Print Names: Write a function print_names that takes names as positional arguments and additional information like country, age, etc., as keyword arguments. Display the names and their additional information.

If you don’t know about “Functions in Python.” just click on read more.

I hope you understand Function Arguments in Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog