Introduction
Keyword arguments let you give values to a function by naming them. This makes your code easier to read and understand.
Jump into concepts and practice - no test required
Keyword arguments let you give values to a function by naming them. This makes your code easier to read and understand.
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.
def greet(name, age): print(f"Hello {name}, you are {age} years old.") greet(name="Alice", age=30)
animal_type and only provide pet_name as a keyword argument.def describe_pet(pet_name, animal_type='dog'): print(f"I have a {animal_type} named {pet_name}.") describe_pet(pet_name='Buddy')
def order_food(main, side, drink): print(f"Main: {main}, Side: {side}, Drink: {drink}") order_food(drink='Water', main='Burger', side='Fries')
This program shows how keyword arguments make it easy to call the function without worrying about the order of inputs.
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')
You can mix positional and keyword arguments, but positional ones must come first.
Using keyword arguments improves code readability and reduces errors.
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.
keyword arguments when calling a function in Python?def greet(name, age): using keyword arguments?parameter=value. greet(name='Alice', age=30) uses name='Alice' and age=30, which is correct.def info(name, age):
print(f"Name: {name}, Age: {age}")
info(age=25, name='Bob')age=25 and name='Bob' are passed, so name gets 'Bob' and age gets 25.def multiply(x, y):
return x * y
result = multiply(x=5, 10)multiply(x=5, 10) has a keyword argument first, then a positional argument, which causes a syntax error.def order(item, quantity=1, price=10):, which call correctly orders 3 items with a price of 15 each using keyword arguments?item and two optional parameters quantity and price with defaults.item argument.