keyword arguments - ibrahimrifats/Back-End-development GitHub Wiki

keyword arguments:

# Keyword Arguments (kwargs):
# Using kwargs, you can pass in any amount of non-keyword arguments.

def sum_of(*args):
    # Function to calculate the sum of non-keyword arguments (args).
    sum = 0
    for x in args:
        sum += x
    return sum

# Example usage of sum_of function with non-keyword arguments:
print(sum_of(5, 6, 3))  # Output: 14
print(sum_of(2, 4, 5, 6, 43, 2, 2, 4, 2))  # Output: 70

def sum_oo(**kwargs):
    # Function to calculate the sum of keyword arguments (kwargs).
    sum = 0
    for k, v in kwargs.items():
        sum += v
    return round(sum, 2)

# Example usage of sum_oo function with keyword arguments:
print(sum_oo(coffee=2.66, cake=43.5, juice=2.57))  # Output: 48.73

In the code, the *args syntax allows you to pass any number of non-keyword arguments to the sum_of function. These arguments are collected into a tuple named args, and the function calculates their sum.

On the other hand, the **kwargs syntax allows you to pass keyword arguments to the sum_oo function. These arguments are collected into a dictionary named kwargs, and the function calculates the sum of the values from the keyword arguments.

The round() function is used in the sum_oo function to round the sum to 2 decimal places for a more precise result.