Loading...
Loading...
Set default values for function parameters
Sometimes a parameter should have a default value that's used if the caller doesn't provide one. This makes functions more flexible ā callers can use the common case with minimal code, but override when needed.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet() # Hello, Guest! (uses default)| Part | What it means |
|---|---|
| `name="Guest"` | Default parameter: if no argument, `name = "Guest"` |
| `greet()` | No argument ā uses the default |
| `greet("Alice")` | Has argument ā overrides the default |
def greet_full(greeting="Hello", name="World"):
print(f"{greeting}, {name}!")
greet_full() # Hello, World!
greet_full("Hi") # Hi, World!
greet_full("Hey", "Python") # Hey, Python!
greet_full(name="Alice") # Hello, Alice! (keyword argument)# ā
OK: non-default first, then defaults
def create_user(name, age=18, city="Unknown"):
print(f"{name}, {age}, from {city}")
# ā Error: default before non-default
# def create_user(name="Guest", age): # SyntaxError!def send_email(to, subject="No Subject", cc=None):
print(f"Sending to: {to}")
print(f"Subject: {subject}")
if cc:
print(f"CC: {cc}")
send_email("[email protected]") # Uses both defaults
send_email("[email protected]", "Meeting Tomorrow") # Custom subject
send_email("[email protected]", cc="[email protected]") # Keyword arg| ā Wrong | Why | ā Right |
|---|---|---|
| `def func(x=5, y):` | Default params must come after non-default | Swap: `def func(y, x=5):` |
| Default is a mutable value like an empty list | Same list shared across calls ā unexpected behavior | Use `None` and create inside: `if x is None: x = []` |
| Assuming defaults are evaluated fresh each call | Defaults are evaluated once at definition time | For mutable defaults, use the `None` pattern |
Define a function power(base, exponent=2) that returns base ** exponent. Call it:
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(2, 10))