Skip to content

Keyword arguments in Python

  • by

Keyword arguments in Python are a way to pass arguments to a function by specifying their corresponding parameter names. Unlike positional arguments, where the arguments are passed based on their position in the function call, keyword arguments allow you to explicitly assign values to specific parameters.

In Python, keyword arguments are passed to a function using the syntax parameter_name=value when calling the function. Here’s the general syntax:

function_name(parameter_name1=value1, parameter_name2=value2, ...)

The key idea behind keyword arguments is that you can provide values for function parameters by using the syntax parameter_name=value when calling the function. This allows you to pass arguments to a function in any order, making the code more readable and less error-prone, especially when dealing with functions that have a large number of parameters.

Keyword arguments in Python example

Here’s an example that demonstrates the usage of keyword arguments in Python:

def greet(name, age):
    print(f"Hello {name}! You are {age} years old.")

# Calling the function with keyword arguments
greet(name="Alice", age=25)

Output:

Keyword arguments in Python

Let’s say you have a function called add_numbers that takes two parameters, a and b, and adds them together. You can call this function using keyword arguments like this:

def add_numbers(a, b):
    result = a + b
    return result

# Calling the function with keyword arguments
sum = add_numbers(a=5, b=10)
print(sum)

Advance example

def calculate_total_cost(item_price, quantity, discount=0, tax_rate=0):
    total_cost = item_price * quantity * (1 - discount) * (1 + tax_rate)
    return total_cost

# Calling the function with keyword arguments
total = calculate_total_cost(item_price=10, quantity=5, discount=0.1, tax_rate=0.05)
print(total)

Output: 47.5

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading