7. Keyword arguments

A keyword argument passes a value by parameter name. Write parameter=value in the call:

  • name="Ada" is a keyword argument; name is the parameter it fills.
  • Keyword arguments can be written in any order.
  • A positional argument must come before keyword arguments: describe("Ada", age=36).
  • You cannot pass the same parameter twice.

Coming from JavaScript? Python has named arguments at the call site (describe(age=36, name="Ada")). JS has no direct equivalent; the closest is passing an options object and destructuring it.

#01

Pass arguments by name

Define describe(name, age) that prints <name> is <age> using an f-string. Call it with both keyword arguments: describe(name="Ada", age=36).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Keyword arguments can change order

Define describe(name, age) as above. Call it with the keywords in reverse order: describe(age=36, name="Ada"). The output is the same because each value is matched by name.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Mix positional and keyword arguments

Define introduce(name, city) that prints <name> lives in <city> using an f-string. Call introduce("Ada", city="London").

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Use keywords with a calculation

Define rectangle(width, height) that returns width * height. Call it as rectangle(height=3, width=4) and print the result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.