How to Use Keyword Arguments in Python: Simple Guide
In Python,
keyword arguments let you pass values to a function by explicitly naming each parameter, like func(name=value). This makes your code clearer and allows arguments to be given in any order.Syntax
Keyword arguments are passed by naming each parameter in the function call. The syntax is function_name(parameter_name=value). This lets you specify which argument goes to which parameter, regardless of their order.
Example parts:
function_name: the function you callparameter_name: the name of the argument in the function definitionvalue: the value you want to assign to that parameter
python
def greet(name, age): print(f"Hello {name}, you are {age} years old.") greet(name="Alice", age=30)
Output
Hello Alice, you are 30 years old.
Example
This example shows how keyword arguments let you call a function with arguments in any order and improve readability.
python
def describe_pet(pet_name, animal_type='dog'): print(f"I have a {animal_type} named {pet_name}.") describe_pet(pet_name='Whiskers', animal_type='cat') describe_pet(animal_type='hamster', pet_name='Harry') describe_pet(pet_name='Buddy')
Output
I have a cat named Whiskers.
I have a hamster named Harry.
I have a dog named Buddy.
Common Pitfalls
Common mistakes include mixing positional and keyword arguments incorrectly or repeating the same argument twice.
Always put positional arguments before keyword arguments in a function call. Also, do not use the same argument name more than once.
python
def add_numbers(a, b): return a + b # Wrong: positional argument after keyword argument # add_numbers(a=5, 10) # This causes a SyntaxError # Wrong: duplicate keyword argument # add_numbers(a=5, a=10) # This causes a SyntaxError # Correct usage result = add_numbers(5, b=10) print(result)
Output
15
Quick Reference
Tips for using keyword arguments:
- Use keyword arguments to improve code readability.
- Keyword arguments can be given in any order.
- Positional arguments must come before keyword arguments.
- Do not repeat the same argument name in a call.
- Functions can have default values for keyword arguments.
Key Takeaways
Keyword arguments let you name parameters when calling a function for clearer code.
You can pass keyword arguments in any order, unlike positional arguments.
Always put positional arguments before keyword arguments in calls.
Avoid repeating the same argument name in a function call.
Use default values with keyword arguments to make parameters optional.