Keyword Arguments
Keyword Arguments
When calling a function, values are usually matched by position.
But Python also gives another way.
You can send values by name.
This is called keyword arguments.
What Are Keyword Arguments?
Keyword arguments are values passed using the parameter name.
This makes your code clearer and easier to read.
Normal Order Example
def user(name, age):
print(name, age)
user("Sara", 20)
Output
Sara 20
Python matches:
"Sara"toname20toage
Using Keyword Arguments
def user(name, age):
print(name, age)
user(age=20, name="Sara")
Output
Sara 20
The order does not matter because the names are used.
Why Keyword Arguments Matter
They help when:
- A function has many values
- You want clearer code
- You want to change the order safely
Another Example
def product(name, price):
print(name, price)
product(price=10, name="Book")
Output
Book 10
Mixing Positional and Keyword Values
You can mix them, but positional values must come first.
def student(name, age):
print(name, age)
student("Ali", age=18)
Output
Ali 18
Common Beginner Mistake
Wrong order:
student(age=18, "Ali")
This causes an error.
Code Along
def city(name, country):
print(name, country)
city(country="Canada", name="Toronto")
Output
Toronto Canada
Mini Challenge
Build a profile function.
Steps:
- Create a function with parameters:
name,age - Print both values
- Call the function using keyword arguments
Expected output:
Maya 25
Real World Use Case
Programs use keyword arguments in forms, settings, reports, and functions with many options.
Quiz
- What are keyword arguments?
- Do values need normal order when using keywords?
- Why are keyword arguments useful?
- Which values must come first when mixing types?
Assignment
Create a function called book with parameters title and price. Call it using keyword arguments.
Summary
You learned that keyword arguments send values by parameter name, making function calls clearer and more flexible.