Function Arguments
Arguments can be passed by position or by name (keyword arguments). A parameter can have a default value. *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict.
Put required parameters first, then defaults. Never use a list or dict as a default value, because it is shared between calls. Use None and create it inside.
Example
def order(item, qty=1, *extras, **options):
print(item, qty, extras, options)
order("rice")
order("rice", 3)
order(qty=2, item="beans")
order("tea", 1, "milk", "sugar", hot=True)Result
rice 1 () {}
rice 3 () {}
beans 2 () {}
tea 1 ('milk', 'sugar') {'hot': True}Exercise
Give the parameter a default of 1.
def buy(item, qty1): pass
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.