Positional and Keyword Arguments
Core idea
Ordinary parameters can receive arguments by position or by name. f(2, 5) supplies values in order, while f(width=2, height=5) explicitly names the parameters. Keyword argument syntax in a call is not a separate assignment in the caller.
def remaining(stock, sold): return stock - sold
print(remaining(9, 2))print(remaining(2, 9))Swapping arguments changes the meaning.
Name the arguments
def remaining(stock, sold): return stock - sold
print(remaining(sold=2, stock=9))print(remaining(9, sold=2))Both calls bind stock to 9 and sold to 2.
Duplicate binding (intentional error)
def remaining(stock, sold): return stock - sold
remaining(9, stock=2, sold=1)Stock is supplied twice, so Python rejects the call before executing the body.
Common mistake
In ordinary calls, put positional arguments before named arguments. Missing required values, unknown names and duplicate bindings raise TypeError.
Practice
Define a subtraction function and call it by position and then with reversed keyword order. Predict both results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Argument binding
Check your understanding of positional and keyword arguments.
What is printed?
def diff(a, b): return a - bprint(diff(b=2, a=7))What is printed?
def diff(a, b): return a - bprint(diff(2, 7))What happens?
def f(a): return af(3, a=4)What determines the binding of an ordinary keyword argument?