0
0
Pythonprogramming~5 mins

Keyword arguments in Python

Choose your learning style9 modes available
Introduction

Keyword arguments let you give values to a function by naming them. This makes your code easier to read and understand.

When a function has many inputs and you want to be clear about which value goes where.
When you want to skip some optional inputs and only set specific ones.
When you want to avoid mistakes by mixing up the order of inputs.
When you want to make your code easier to read for others or yourself later.
Syntax
Python
def function_name(param1=value1, param2=value2):
    # function body

function_name(param1=valueA, param2=valueB)

You write the parameter name followed by an equal sign and the value.

Order does not matter when calling with keyword arguments.

Examples
Here, we call the function using keyword arguments to clearly show which value is for which parameter.
Python
def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet(name="Alice", age=30)
We use a default value for animal_type and only provide pet_name as a keyword argument.
Python
def describe_pet(pet_name, animal_type='dog'):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet(pet_name='Buddy')
Keyword arguments let us give values in any order.
Python
def order_food(main, side, drink):
    print(f"Main: {main}, Side: {side}, Drink: {drink}")

order_food(drink='Water', main='Burger', side='Fries')
Sample Program

This program shows how keyword arguments make it easy to call the function without worrying about the order of inputs.

Python
def book_flight(destination, date, seat_class='Economy'):
    print(f"Booking a {seat_class} seat to {destination} on {date}.")

book_flight(date='2024-07-01', destination='Paris')
book_flight(destination='Tokyo', date='2024-08-15', seat_class='Business')
OutputSuccess
Important Notes

You can mix positional and keyword arguments, but positional ones must come first.

Using keyword arguments improves code readability and reduces errors.

Summary

Keyword arguments let you name inputs when calling a function.

They make your code clearer and easier to understand.

You can give values in any order when using keyword arguments.