Functions, args, kwargs, defaults
def name(params): ... return value. *args collects positional, **kwargs collects keyword.
script.py
v3.1
Python output
click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
The output will appear here.
🧠 How it works
def name(params): body return value. Default args use '=' — evaluated ONCE at def time (mutable defaults like def f(x=[]) are a famous footgun!). *args collects extra positional args into a tuple. **kwargs collects extra keyword args into a dict. Order: positional, *args, keyword-only, **kwargs. Passing *list and **dict unpacks them into separate args: f(*[1,2,3]) is f(1, 2, 3). Functions are first-class — you can pass them as args, return them, store in variables.
✏️ Try these changes
-
Change greeting='Hello' to greeting='Hi'→ default greeting changes -
Add a new parameter punctuation='!' and append it to msg→ greeting ends with the punctuation -
Change sum_all(1,2,3,4,5) to sum_all(*range(1, 6))→ unpacks range into args — same result -
Call greet() with no args→ TypeError — name is required