Default and Keyword Arguments

Give parameters default values, then call the same function four ways: positions, defaults, and names.

Python · beginner · 7 min · 17 steps · free

What you'll learn

defaults.py

def greet(name, greeting="Hello", times=1):
    return (greeting + ", " + name + "! ") * times

a = greet("Asha")
b = greet("Ben", "Hi")
c = greet("Cara", times=2)                 # keyword argument: skip greeting
d = greet(greeting="Hey", name="Dev")      # any order with keywords
print(a)
print(b)
print(c)
print(d)

Step by step

  1. greeting and times have defaults, so callers may leave them out.
  2. Only the name is given: greeting and times use their defaults.
  3. The function returns (greeting + ", " + name + "! ") * times.
  4. Only the name is given: greeting and times use their defaults.
  5. "Hi" fills the second parameter by position.
  6. The function returns (greeting + ", " + name + "! ") * times.
  7. "Hi" fills the second parameter by position.
  8. times=2 sets a parameter by name, skipping greeting, which keeps its default.
  9. The function returns (greeting + ", " + name + "! ") * times.
  10. greet() has finished, so its names are gone. The value it returned, 'Hello, Cara! Hello, Cara! ', is stored in c.
  11. With keywords, order does not matter.
  12. The function returns (greeting + ", " + name + "! ") * times.
  13. greet() has finished, so its names are gone. The value it returned, 'Hey, Dev! ', is stored in d.
  14. It prints Hello, Asha! .
  15. It prints Hi, Ben! .
  16. It prints Hello, Cara! Hello, Cara! .
  17. One function, four styles of call. Defaults make arguments optional; keywords make calls self-explaining.

Common mistakes

Best practices

Key takeaways

Check yourself

def f(a, b=1): is f(b=3, a=1) allowed?

Answer: Yes. Keyword arguments can come in any order.

Why avoid def f(items=[])?

Answer: The same list is shared by every call. Defaults are created once, when def runs.

·

More in Functions