Parameters and Arguments

Positional, keyword, default arguments

Interview Relevant: Critical for interviews

Parameters and Arguments

Different ways to pass arguments to functions.

Code Examples

Function parameters and arguments.

python
1# Positional arguments
2def add(a, b):
3    return a + b
4add(1, 2)  # 3
5
6# Keyword arguments
7add(a=1, b=2)
8add(b=2, a=1)  # Order doesn't matter
9
10# Default arguments
11def greet(name, greeting="Hello"):
12    return f"{greeting}, {name}!"
13greet("Alice")           # Hello, Alice!
14greet("Bob", "Hi")       # Hi, Bob!
15
16# DANGER: Mutable default argument!
17def bad(lst=[]):     # DON'T do this!
18    lst.append(1)
19    return lst
20
21def good(lst=None):  # Do this instead
22    if lst is None:
23        lst = []
24    lst.append(1)
25    return lst
26
27# Keyword-only arguments (after *)
28def func(a, *, b, c):
29    pass
30func(1, b=2, c=3)  # Must use keywords

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In