Level 1
0 / 100 XP

Default arguments

Sometimes a parameter has a sensible default, and you'd rather not force the caller to supply it every time. Python lets you give a parameter a default value.

Giving a parameter a default

Assign a value in the def line. That value is used whenever the caller leaves the argument out:

Python
def greet(name, greeting="Hello"): print(greeting + ", " + name) greet("Alice") # Hello, Alice (uses the default) greet("Sam", "Hi") # Hi, Sam (overrides the default)

The first call doesn't pass greeting, so Python uses "Hello". The second call passes "Hi", which overrides the default.

The rule: defaults come last

Parameters with defaults must come after parameters without them:

Python
def greet(name, greeting="Hello"): # OK ... # def greet(greeting="Hello", name): # ERROR

This keeps Python from getting confused about which argument is which.

Key takeaways

  • A default value is given in the def: def f(x, y=10):.
  • Callers can omit a defaulted argument or pass one to override it.
  • Parameters with defaults must come after those without.