Keyword parameters
- Python course
- Beginner
- Lesson 78/116
- 4 min
Learn to pass keyword parameters.
Keyword parameters
With keyword calls you can write the parameter name explicitly; order becomes irrelevant:
def introduce(name, age):
print(name, age)
introduce(age=28, name="Ayse") # Ayse 28These calls are readable and safe. In functions with many parameters, the meaning of each value is clear.
Keyword calls also prevent order-related mistakes.
Mixed positional and keyword
A call can mix positional and keyword; but positional comes first, then keyword:
introduce("Ayse", age=28) # valid
introduce(name="Ayse", 28) # SyntaxErrorPython requires this rule; otherwise a SyntaxError is raised. This rule is called positional-first.
Mixed calls are useful for readability; but you must respect the order.
Practice Write a keyword call
Define a function called introduce with name and age parameters. The body does print(name, age). Call it with the keyword call introduce(age=28, name="Ayse").
Starter code
# Define the introduce functionSample solution
def introduce(name, age):
print(name, age)
introduce(age=28, name="Ayse")Expected output
Ayse 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the keyword call
introduce(____=28, name="Ayse")
introduce(age=28, name="Ayse")
Explanation: age=28 is a keyword call.
2 Match keyword features
| Term | Meaning |
|---|---|
name="Ayse" |
Keyword |
order irrelevant |
Advantage |
SyntaxError |
Positional after keyword |
age=28 |
Keyword example |
3 Which is a valid call?
- introduce(name="Ayse", 28)
- introduce(age=28, "Ayse")
- introduce(name="Ayse", age 28)
- introduce("Ayse", age=28) Correct answer
Explanation: Positional first, then keyword.