Functions & Scope
Default Arguments
Optional Parameters
Your greet() function usually says "Hello" but sometimes needs "Hi" or "Hey".
Default arguments let callers omit parameters when the default is fine, while
still allowing customization when needed.
Basic default values
Give parameters default values.
def main():
print("=== Default Arguments ===\n")
# Without default - must provide both
greet_formal("Alice", "Good morning")
# With default - greeting is optional
greet("Bob") # Uses default "Hello"
greet("Charlie", "Hey") # Overrides default
greet("Diana", "Good evening")
print("\n=== Common Pattern ===")
# Default makes common case simple
# Special cases still possible
greet("Everyone") # 90% of calls use default
greet("VIP", "Welcome, dear") # 10% need custom
def greet_formal(name, greeting):
"""Both arguments required."""
print(f"{greeting}, {name}!")
def greet(name, greeting="Hello"):
"""greeting has default value."""
print(f"{greeting}, {name}!")
def greet_polite(name, greeting="Hello", punctuation="!"):
"""Multiple defaults."""
print(f"{greeting}, {name}{punctuation}")
if __name__ == "__main__":
main()
def main():
1#@var=default,formal2def main():3 print("=== Default Arguments ===\n")4 5 # Without default - must provide both #?greet6 greet_formal("Alice", "Good morning")output=== Default Arguments ===def greet_formal(name, greeting): #?required
5 # Without default - must provide both #?greet6 greet_formal("Alice", "Good morning")7 8 # With default - greeting is optional9 greet("Bob") # Uses default "Hello"10 greet("Charlie", "Hey") # Overrides default11 greet("Diana", "Good evening")12 13 print("\n=== Common Pattern ===")14 # Default makes common case simple15 # Special cases still possible16 17 greet("Everyone") # 90% of calls use default18 greet("VIP", "Welcome, dear") # 10% need custom1920def greet_formal(nameAlice, greetingGood morning): #?required21 """Both arguments required."""22 print(f"{greetingGood morning}, {nameAlice}!")outputGood morning, Alice!def greet(name, greeting="Hello"): #?default
pass 1 of 58 # With default - greeting is optional9 greet("Bob") # Uses default "Hello"10 greet("Charlie", "Hey") # Overrides default11 greet("Diana", "Good evening")12 13 print("\n=== Common Pattern ===")14 # Default makes common case simple15 # Special cases still possible16 17 greet("Everyone") # 90% of calls use default18 greet("VIP", "Welcome, dear") # 10% need custom1920def greet_formal(name, greeting): #?required21 """Both arguments required."""22 print(f"{greeting}, {name}!")2324def greet(nameBob, greetingHello="Hello"): #?default25 """greeting has default value."""26 print(f"{greetingHello}, {nameBob}!")outputHello, Bob!All 5 passes — pass 1 is the card above pass namegreeting1 Bob Hello 2 Charlie Hey 3 Diana Good evening 4 Everyone Hello 5 VIP Welcome, dear main()
34if __name__ == "__main__":35 main()36#@help greet
Parameters with defaults can be omitted when calling the function.
Keyword arguments skip positional defaults
Use keyword syntax to specify later parameters.
def main():
print("=== Keyword Arguments ===\n")
# Positional: order matters
print("Positional order:")
describe_pet("Hamster", "Harry")
describe_pet("Dog", "Buddy")
# Keyword: name=value, order doesn't matter
print("\nKeyword arguments:")
describe_pet(pet_name="Whiskers", animal_type="Cat")
describe_pet(animal_type="Fish", pet_name="Nemo") # Reversed!
# Mix positional and keyword
print("\nMixed:")
describe_pet("Rabbit", pet_name="Thumper")
# Skip middle defaults with keywords!
print("\nSkipping defaults:")
format_text("hello world", uppercase=True) # Skip width
format_text("hello world", width=20) # Skip uppercase
format_text("hello world", uppercase=True, width=15) # All specified
def describe_pet(animal_type, pet_name):
"""Describe a pet."""
print(f" I have a {animal_type} named {pet_name}.")
def format_text(text, width=0, uppercase=False):
"""Format text with optional width and case."""
result = text.upper() if uppercase else text
if width > 0:
result = result.center(width)
print(f" '{result}'")
if __name__ == "__main__":
main()
def main():
1#@var=default,explicit2def main():3 print("=== Keyword Arguments ===\n")4 5 # Positional: order matters6 print("Positional order:")7 describe_pet("Hamster", "Harry") #?positional8 describe_pet("Dog", "Buddy")output=== Keyword Arguments === Positional order:def describe_pet(animal_type, pet_name):
pass 1 of 56 print("Positional order:")7 describe_pet("Hamster", "Harry") #?positional8 describe_pet("Dog", "Buddy")9 10 # Keyword: name=value, order doesn't matter11 print("\nKeyword arguments:")12 describe_pet(pet_name="Whiskers", animal_type="Cat") #?keyword13 describe_pet(animal_type="Fish", pet_name="Nemo") # Reversed!14 15 # Mix positional and keyword #?mix16 print("\nMixed:")17 describe_pet("Rabbit", pet_name="Thumper")18 19 # Skip middle defaults with keywords! #?skip20 print("\nSkipping defaults:")21 format_text("hello world", uppercase=True) # Skip width22 format_text("hello world", width=20) # Skip uppercase23 format_text("hello world", uppercase=True, width=15) # All specified #@var=_,!2425def describe_pet(animal_typeHamster, pet_nameHarry):26 """Describe a pet."""27 print(f" I have a {animal_typeHamster} named {pet_nameHarry}.")output I have a Hamster named Harry.All 5 passes — pass 1 is the card above pass animal_typepet_namewidthresult1 Hamster Harry — — 2 Dog Buddy — — 3 Cat Whiskers — — 4 Fish Nemo — — 5 Rabbit Thumper 20 hello world → hello world result ← HELLO WORLD
pass 1 of 320 print("\nSkipping defaults:")21 format_text("hello world", uppercase=True) # Skip width22 format_text("hello world", width=20) # Skip uppercase23 format_text("hello world", uppercase=True, width=15) # All specified #@var=_,!2425def describe_pet(animal_type, pet_name):26 """Describe a pet."""27 print(f" I have a {animal_type} named {pet_name}.")2829def format_text(texthello world, width0=0, uppercaseTrue=FalseFalse): #?format30 """Format text with optional width and case."""31 result→ HELLO WORLD = texthello world.upper() if uppercaseTrue else text32 if width > 0:33 result = result.center(width)34 print(f" '{resultHELLO WORLD}'")output 'HELLO WORLD'All 3 passes — pass 1 is the card above pass widthuppercaseresult1 0 True HELLO WORLD 2 20 False hello world 3 15 True HELLO WORLD result ← hello world
pass 1 of 231result = text.upper() if uppercase else text32if width20 > 0:33 result→ hello world = result.center(width20)34print(f" '{result}'")print(f" '{result}'")
21 format_text("hello world", uppercase=True) # Skip width22 format_text("hello world", width=20) # Skip uppercase23 format_text("hello world", uppercase=True, width=15) # All specified #@var=_,!2425def describe_pet(animal_type, pet_name):26 """Describe a pet."""27 print(f" I have a {animal_type} named {pet_name}.")2829def format_text(text, width=0, uppercase=False): #?format30 """Format text with optional width and case."""31 result = text.upper() if uppercase else text32 if width > 0:33 result = result.center(width)34 print(f" '{result hello world }'")output ' hello world 'result ← HELLO WORLD
pass 2 of 231result = text.upper() if uppercase else text32if width15 > 0:33 result→ HELLO WORLD = result.center(width15)34print(f" '{result}'")print(f" '{result}'")
22 format_text("hello world", width=20) # Skip uppercase23 format_text("hello world", uppercase=True, width=15) # All specified #@var=_,!2425def describe_pet(animal_type, pet_name):26 """Describe a pet."""27 print(f" I have a {animal_type} named {pet_name}.")2829def format_text(text, width=0, uppercase=False): #?format30 """Format text with optional width and case."""31 result = text.upper() if uppercase else text32 if width > 0:33 result = result.center(width)34 print(f" '{result HELLO WORLD }'")output ' HELLO WORLD 'main()
36if __name__ == "__main__":37 main()38#@help positional
func(c=30) skips a and b if they have defaults.
Multiple default parameters
Functions can have several parameters with defaults.
def main():
print("=== Multiple Default Arguments ===\n")
# Using all defaults
print("All defaults:")
make_coffee()
# Override some
print("\nCustom orders:")
make_coffee(size="large")
make_coffee(milk=True)
make_coffee(sugar=2)
make_coffee(size="small", sugar=3)
# Override all
print("\nFully customized:")
custom_size = "large"
sugar_count = 2
make_coffee(custom_size, True, sugar_count) # positional
make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword
# Configuration pattern
print("\n=== Configuration Pattern ===")
print_report()
print_report(title="Sales Report", columns=3)
print_report(show_header=True, title="Status")
def make_coffee(size="medium", milk=False, sugar=0):
"""Make coffee with customizable options."""
order = f" {size.capitalize()} coffee"
if milk:
order += " with milk"
if sugar > 0:
order += f", {sugar} sugar(s)"
print(order)
def print_report(title="Report", columns=2, show_header=False):
"""Print a configurable report."""
if show_header:
print(f" === {title} ===")
else:
print(f" {title}")
print(f" ({columns} columns)")
if __name__ == "__main__":
main()
def main():
print("=== Multiple Default Arguments ===\n")
# Using all defaults
print("All defaults:")
make_coffee()
# Override some
print("\nCustom orders:")
make_coffee(size="large")
make_coffee(milk=True)
make_coffee(sugar=2)
make_coffee(size="small", sugar=3)
# Override all
print("\nFully customized:")
custom_size = "small"
sugar_count = 2
make_coffee(custom_size, True, sugar_count) # positional
make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword
# Configuration pattern
print("\n=== Configuration Pattern ===")
print_report()
print_report(title="Sales Report", columns=3)
print_report(show_header=True, title="Status")
def make_coffee(size="medium", milk=False, sugar=0):
"""Make coffee with customizable options."""
order = f" {size.capitalize()} coffee"
if milk:
order += " with milk"
if sugar > 0:
order += f", {sugar} sugar(s)"
print(order)
def print_report(title="Report", columns=2, show_header=False):
"""Print a configurable report."""
if show_header:
print(f" === {title} ===")
else:
print(f" {title}")
print(f" ({columns} columns)")
if __name__ == "__main__":
main()
def main():
print("=== Multiple Default Arguments ===\n")
# Using all defaults
print("All defaults:")
make_coffee()
# Override some
print("\nCustom orders:")
make_coffee(size="large")
make_coffee(milk=True)
make_coffee(sugar=2)
make_coffee(size="small", sugar=3)
# Override all
print("\nFully customized:")
custom_size = "large"
sugar_count = 1
make_coffee(custom_size, True, sugar_count) # positional
make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword
# Configuration pattern
print("\n=== Configuration Pattern ===")
print_report()
print_report(title="Sales Report", columns=3)
print_report(show_header=True, title="Status")
def make_coffee(size="medium", milk=False, sugar=0):
"""Make coffee with customizable options."""
order = f" {size.capitalize()} coffee"
if milk:
order += " with milk"
if sugar > 0:
order += f", {sugar} sugar(s)"
print(order)
def print_report(title="Report", columns=2, show_header=False):
"""Print a configurable report."""
if show_header:
print(f" === {title} ===")
else:
print(f" {title}")
print(f" ({columns} columns)")
if __name__ == "__main__":
main()
def main():
print("=== Multiple Default Arguments ===\n")
# Using all defaults
print("All defaults:")
make_coffee()
# Override some
print("\nCustom orders:")
make_coffee(size="large")
make_coffee(milk=True)
make_coffee(sugar=2)
make_coffee(size="small", sugar=3)
# Override all
print("\nFully customized:")
custom_size = "large"
sugar_count = 3
make_coffee(custom_size, True, sugar_count) # positional
make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword
# Configuration pattern
print("\n=== Configuration Pattern ===")
print_report()
print_report(title="Sales Report", columns=3)
print_report(show_header=True, title="Status")
def make_coffee(size="medium", milk=False, sugar=0):
"""Make coffee with customizable options."""
order = f" {size.capitalize()} coffee"
if milk:
order += " with milk"
if sugar > 0:
order += f", {sugar} sugar(s)"
print(order)
def print_report(title="Report", columns=2, show_header=False):
"""Print a configurable report."""
if show_header:
print(f" === {title} ===")
else:
print(f" {title}")
print(f" ({columns} columns)")
if __name__ == "__main__":
main()
def main():
1#@var=default,config2def main():3 print("=== Multiple Default Arguments ===\n")4 5 # Using all defaults #?alldefault6 print("All defaults:")7 make_coffee()output=== Multiple Default Arguments === All defaults:order ← Medium coffee
pass 1 of 76 print("All defaults:")7 make_coffee()8 9 # Override some #?override10 print("\nCustom orders:")11 make_coffee(size="large")12 make_coffee(milk=True)13 make_coffee(sugar=2)14 make_coffee(size="small", sugar=3)15 16 # Override all17 print("\nFully customized:")18 custom_size = "large" #@custom_size="small"19 sugar_count = 2 #@sugar_count=1, 320 make_coffee(custom_size, True, sugar_count) # positional21 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword22 23 # Configuration pattern #@var=_,!24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(sizemedium="medium", milkFalse=FalseFalse, sugar0=0): #?params30 """Make coffee with customizable options."""31 order→ Medium coffee = f" {sizemedium.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order Medium coffee)output Medium coffee Custom orders:All 7 passes — pass 1 is the card above pass sizemilksugarorder1 medium False 0 Medium coffee 2 large False 0 Large coffee 3 medium True 0 Medium coffee 4 medium False 2 Medium coffee 5 small False 3 Small coffee 6 large True 2 Large coffee 7 large True 2 Large coffee order ← Medium coffee with milk
pass 1 of 331order = f" {size.capitalize()} coffee"32if milkTrue:33 order→ Medium coffee with milk += " with milk"34if sugar > 0:All 3 passes — pass 1 is the card above pass order1 Medium coffee → Medium coffee with milk 2 Large coffee → Large coffee with milk 3 Large coffee → Large coffee with milk print(order)
11 make_coffee(size="large")12 make_coffee(milk=True)13 make_coffee(sugar=2)14 make_coffee(size="small", sugar=3)15 16 # Override all17 print("\nFully customized:")18 custom_size = "large" #@custom_size="small"19 sugar_count = 2 #@sugar_count=1, 320 make_coffee(custom_size, True, sugar_count) # positional21 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword22 23 # Configuration pattern #@var=_,!24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order Medium coffee with milk)output Medium coffee with milkorder ← Medium coffee, 2 sugar(s)
pass 1 of 433 order += " with milk"34if sugar2 > 0:35 order→ Medium coffee, 2 sugar(s) += f", {sugar2} sugar(s)"36print(order)All 4 passes — pass 1 is the card above pass sugarorder1 2 Medium coffee → Medium coffee, 2 sugar(s) 2 3 Small coffee → Small coffee, 3 sugar(s) 3 2 Large coffee with milk → Large coffee with milk, 2 sugar(s) 4 2 Large coffee with milk → Large coffee with milk, 2 sugar(s) print(order)
12 make_coffee(milk=True)13 make_coffee(sugar=2)14 make_coffee(size="small", sugar=3)15 16 # Override all17 print("\nFully customized:")18 custom_size = "large" #@custom_size="small"19 sugar_count = 2 #@sugar_count=1, 320 make_coffee(custom_size, True, sugar_count) # positional21 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword22 23 # Configuration pattern #@var=_,!24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order Medium coffee, 2 sugar(s))output Medium coffee, 2 sugar(s)custom_size ← large, sugar_count ← 2
13 make_coffee(sugar=2)14 make_coffee(size="small", sugar=3)15 16 # Override all17 print("\nFully customized:")18 custom_size→ large = "large" #@custom_size="small"19 sugar_count→ 2 = 2 #@sugar_count=1, 320 make_coffee(custom_sizelarge, True, sugar_count2) # positional21 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword22 23 # Configuration pattern #@var=_,!24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order Small coffee, 3 sugar(s))output Small coffee, 3 sugar(s) Fully customized:print(order)
19 sugar_count = 2 #@sugar_count=1, 320 make_coffee(custom_sizelarge, True, sugar_count2) # positional21 make_coffee(size=custom_sizelarge, milk=True, sugar=sugar_count2) # keyword22 23 # Configuration pattern #@var=_,!24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order Large coffee with milk, 2 sugar(s))output Large coffee with milk, 2 sugar(s)print(order)
20 make_coffee(custom_size, True, sugar_count) # positional21 make_coffee(size=custom_sizelarge, milk=True, sugar=sugar_count2) # keyword22 23 # Configuration pattern #@var=_,!24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order Large coffee with milk, 2 sugar(s))output Large coffee with milk, 2 sugar(s) === Configuration Pattern ===def print_report(title="Report", columns=2, show_header=False):
pass 1 of 338#@var=_,!39def print_report(titleReport="Report", columns2=2, show_headerFalse=FalseFalse):40 """Print a configurable report."""41 if show_header:All 3 passes — pass 1 is the card above pass titlecolumnsshow_header1 Report 2 False 2 Sales Report 3 False 3 Status 2 True else:
pass 1 of 241if show_header:42 print(f" === {title} ===")43else:44 print(f" {titleReport}")45print(f" ({columns} columns)")output Reportprint(f" ({columns} columns)")
24 print("\n=== Configuration Pattern ===") #@var=_,!25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order)3738#@var=_,!39def print_report(title="Report", columns=2, show_header=False):40 """Print a configurable report."""41 if show_header:42 print(f" === {title} ===")43 else:44 print(f" {title}")45 print(f" ({columns2} columns)")46#@var=_,!output (2 columns)else:
pass 2 of 241if show_header:42 print(f" === {title} ===")43else:44 print(f" {titleSales Report}")45print(f" ({columns} columns)")output Sales Reportprint(f" ({columns} columns)")
25 print_report() #@var=_,!26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order)3738#@var=_,!39def print_report(title="Report", columns=2, show_header=False):40 """Print a configurable report."""41 if show_header:42 print(f" === {title} ===")43 else:44 print(f" {title}")45 print(f" ({columns3} columns)")46#@var=_,!output (3 columns)if show_header:
40"""Print a configurable report."""41if show_headerTrue:42 print(f" === {titleStatus} ===")43else:output === Status ===print(f" ({columns} columns)")
26 print_report(title="Sales Report", columns=3) #@var=_,!27 print_report(show_header=True, title="Status") #@var=_,!2829def make_coffee(size="medium", milk=False, sugar=0): #?params30 """Make coffee with customizable options."""31 order = f" {size.capitalize()} coffee"32 if milk:33 order += " with milk"34 if sugar > 0:35 order += f", {sugar} sugar(s)"36 print(order)3738#@var=_,!39def print_report(title="Report", columns=2, show_header=False):40 """Print a configurable report."""41 if show_header:42 print(f" === {title} ===")43 else:44 print(f" {title}")45 print(f" ({columns2} columns)")46#@var=_,!output (2 columns)main()
48if __name__ == "__main__":49 main()50#@help alldefault
def main():
1def main():2 print("=== Multiple Default Arguments ===\n")3 4 # Using all defaults5 print("All defaults:")6 make_coffee()output=== Multiple Default Arguments === All defaults:order ← Medium coffee
pass 1 of 75 print("All defaults:")6 make_coffee()7 8 # Override some9 print("\nCustom orders:")10 make_coffee(size="large")11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "small"18 sugar_count = 219 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(sizemedium="medium", milkFalse=FalseFalse, sugar0=0):29 """Make coffee with customizable options."""30 order→ Medium coffee = f" {sizemedium.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee)output Medium coffee Custom orders:All 7 passes — pass 1 is the card above pass sizemilksugarorder1 medium False 0 Medium coffee 2 large False 0 Large coffee 3 medium True 0 Medium coffee 4 medium False 2 Medium coffee 5 small False 3 Small coffee 6 small True 2 Small coffee 7 small True 2 Small coffee order ← Medium coffee with milk
pass 1 of 330order = f" {size.capitalize()} coffee"31if milkTrue:32 order→ Medium coffee with milk += " with milk"33if sugar > 0:All 3 passes — pass 1 is the card above pass order1 Medium coffee → Medium coffee with milk 2 Small coffee → Small coffee with milk 3 Small coffee → Small coffee with milk print(order)
10 make_coffee(size="large")11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "small"18 sugar_count = 219 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee with milk)output Medium coffee with milkorder ← Medium coffee, 2 sugar(s)
pass 1 of 432 order += " with milk"33if sugar2 > 0:34 order→ Medium coffee, 2 sugar(s) += f", {sugar2} sugar(s)"35print(order)All 4 passes — pass 1 is the card above pass sugarorder1 2 Medium coffee → Medium coffee, 2 sugar(s) 2 3 Small coffee → Small coffee, 3 sugar(s) 3 2 Small coffee with milk → Small coffee with milk, 2 sugar(s) 4 2 Small coffee with milk → Small coffee with milk, 2 sugar(s) print(order)
11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "small"18 sugar_count = 219 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee, 2 sugar(s))output Medium coffee, 2 sugar(s)custom_size ← small, sugar_count ← 2
12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size→ small = "small"18 sugar_count→ 2 = 219 make_coffee(custom_sizesmall, True, sugar_count2) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Small coffee, 3 sugar(s))output Small coffee, 3 sugar(s) Fully customized:print(order)
18 sugar_count = 219 make_coffee(custom_sizesmall, True, sugar_count2) # positional20 make_coffee(size=custom_sizesmall, milk=True, sugar=sugar_count2) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Small coffee with milk, 2 sugar(s))output Small coffee with milk, 2 sugar(s)print(order)
19 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_sizesmall, milk=True, sugar=sugar_count2) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Small coffee with milk, 2 sugar(s))output Small coffee with milk, 2 sugar(s) === Configuration Pattern ===def print_report(title="Report", columns=2, show_header=False):
pass 1 of 337def print_report(titleReport="Report", columns2=2, show_headerFalse=FalseFalse):38 """Print a configurable report."""39 if show_header:All 3 passes — pass 1 is the card above pass titlecolumnsshow_header1 Report 2 False 2 Sales Report 3 False 3 Status 2 True else:
pass 1 of 239if show_header:40 print(f" === {title} ===")41else:42 print(f" {titleReport}")43print(f" ({columns} columns)")output Reportprint(f" ({columns} columns)")
23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns2} columns)")output (2 columns)else:
pass 2 of 239if show_header:40 print(f" === {title} ===")41else:42 print(f" {titleSales Report}")43print(f" ({columns} columns)")output Sales Reportprint(f" ({columns} columns)")
24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns3} columns)")output (3 columns)if show_header:
38"""Print a configurable report."""39if show_headerTrue:40 print(f" === {titleStatus} ===")41else:output === Status ===print(f" ({columns} columns)")
25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns2} columns)")output (2 columns)main()
45if __name__ == "__main__":46 main()
def main():
1def main():2 print("=== Multiple Default Arguments ===\n")3 4 # Using all defaults5 print("All defaults:")6 make_coffee()output=== Multiple Default Arguments === All defaults:order ← Medium coffee
pass 1 of 75 print("All defaults:")6 make_coffee()7 8 # Override some9 print("\nCustom orders:")10 make_coffee(size="large")11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "large"18 sugar_count = 119 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(sizemedium="medium", milkFalse=FalseFalse, sugar0=0):29 """Make coffee with customizable options."""30 order→ Medium coffee = f" {sizemedium.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee)output Medium coffee Custom orders:All 7 passes — pass 1 is the card above pass sizemilksugarorder1 medium False 0 Medium coffee 2 large False 0 Large coffee 3 medium True 0 Medium coffee 4 medium False 2 Medium coffee 5 small False 3 Small coffee 6 large True 1 Large coffee 7 large True 1 Large coffee order ← Medium coffee with milk
pass 1 of 330order = f" {size.capitalize()} coffee"31if milkTrue:32 order→ Medium coffee with milk += " with milk"33if sugar > 0:All 3 passes — pass 1 is the card above pass order1 Medium coffee → Medium coffee with milk 2 Large coffee → Large coffee with milk 3 Large coffee → Large coffee with milk print(order)
10 make_coffee(size="large")11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "large"18 sugar_count = 119 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee with milk)output Medium coffee with milkorder ← Medium coffee, 2 sugar(s)
pass 1 of 432 order += " with milk"33if sugar2 > 0:34 order→ Medium coffee, 2 sugar(s) += f", {sugar2} sugar(s)"35print(order)All 4 passes — pass 1 is the card above pass sugarorder1 2 Medium coffee → Medium coffee, 2 sugar(s) 2 3 Small coffee → Small coffee, 3 sugar(s) 3 1 Large coffee with milk → Large coffee with milk, 1 sugar(s) 4 1 Large coffee with milk → Large coffee with milk, 1 sugar(s) print(order)
11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "large"18 sugar_count = 119 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee, 2 sugar(s))output Medium coffee, 2 sugar(s)custom_size ← large, sugar_count ← 1
12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size→ large = "large"18 sugar_count→ 1 = 119 make_coffee(custom_sizelarge, True, sugar_count1) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Small coffee, 3 sugar(s))output Small coffee, 3 sugar(s) Fully customized:print(order)
18 sugar_count = 119 make_coffee(custom_sizelarge, True, sugar_count1) # positional20 make_coffee(size=custom_sizelarge, milk=True, sugar=sugar_count1) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Large coffee with milk, 1 sugar(s))output Large coffee with milk, 1 sugar(s)print(order)
19 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_sizelarge, milk=True, sugar=sugar_count1) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Large coffee with milk, 1 sugar(s))output Large coffee with milk, 1 sugar(s) === Configuration Pattern ===def print_report(title="Report", columns=2, show_header=False):
pass 1 of 337def print_report(titleReport="Report", columns2=2, show_headerFalse=FalseFalse):38 """Print a configurable report."""39 if show_header:All 3 passes — pass 1 is the card above pass titlecolumnsshow_header1 Report 2 False 2 Sales Report 3 False 3 Status 2 True else:
pass 1 of 239if show_header:40 print(f" === {title} ===")41else:42 print(f" {titleReport}")43print(f" ({columns} columns)")output Reportprint(f" ({columns} columns)")
23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns2} columns)")output (2 columns)else:
pass 2 of 239if show_header:40 print(f" === {title} ===")41else:42 print(f" {titleSales Report}")43print(f" ({columns} columns)")output Sales Reportprint(f" ({columns} columns)")
24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns3} columns)")output (3 columns)if show_header:
38"""Print a configurable report."""39if show_headerTrue:40 print(f" === {titleStatus} ===")41else:output === Status ===print(f" ({columns} columns)")
25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns2} columns)")output (2 columns)main()
45if __name__ == "__main__":46 main()
def main():
1def main():2 print("=== Multiple Default Arguments ===\n")3 4 # Using all defaults5 print("All defaults:")6 make_coffee()output=== Multiple Default Arguments === All defaults:order ← Medium coffee
pass 1 of 75 print("All defaults:")6 make_coffee()7 8 # Override some9 print("\nCustom orders:")10 make_coffee(size="large")11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "large"18 sugar_count = 319 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(sizemedium="medium", milkFalse=FalseFalse, sugar0=0):29 """Make coffee with customizable options."""30 order→ Medium coffee = f" {sizemedium.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee)output Medium coffee Custom orders:All 7 passes — pass 1 is the card above pass sizemilksugarorder1 medium False 0 Medium coffee 2 large False 0 Large coffee 3 medium True 0 Medium coffee 4 medium False 2 Medium coffee 5 small False 3 Small coffee 6 large True 3 Large coffee 7 large True 3 Large coffee order ← Medium coffee with milk
pass 1 of 330order = f" {size.capitalize()} coffee"31if milkTrue:32 order→ Medium coffee with milk += " with milk"33if sugar > 0:All 3 passes — pass 1 is the card above pass order1 Medium coffee → Medium coffee with milk 2 Large coffee → Large coffee with milk 3 Large coffee → Large coffee with milk print(order)
10 make_coffee(size="large")11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "large"18 sugar_count = 319 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee with milk)output Medium coffee with milkorder ← Medium coffee, 2 sugar(s)
pass 1 of 432 order += " with milk"33if sugar2 > 0:34 order→ Medium coffee, 2 sugar(s) += f", {sugar2} sugar(s)"35print(order)All 4 passes — pass 1 is the card above pass sugarorder1 2 Medium coffee → Medium coffee, 2 sugar(s) 2 3 Small coffee → Small coffee, 3 sugar(s) 3 3 Large coffee with milk → Large coffee with milk, 3 sugar(s) 4 3 Large coffee with milk → Large coffee with milk, 3 sugar(s) print(order)
11 make_coffee(milk=True)12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size = "large"18 sugar_count = 319 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Medium coffee, 2 sugar(s))output Medium coffee, 2 sugar(s)custom_size ← large, sugar_count ← 3
12 make_coffee(sugar=2)13 make_coffee(size="small", sugar=3)14 15 # Override all16 print("\nFully customized:")17 custom_size→ large = "large"18 sugar_count→ 3 = 319 make_coffee(custom_sizelarge, True, sugar_count3) # positional20 make_coffee(size=custom_size, milk=True, sugar=sugar_count) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Small coffee, 3 sugar(s))output Small coffee, 3 sugar(s) Fully customized:print(order)
18 sugar_count = 319 make_coffee(custom_sizelarge, True, sugar_count3) # positional20 make_coffee(size=custom_sizelarge, milk=True, sugar=sugar_count3) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Large coffee with milk, 3 sugar(s))output Large coffee with milk, 3 sugar(s)print(order)
19 make_coffee(custom_size, True, sugar_count) # positional20 make_coffee(size=custom_sizelarge, milk=True, sugar=sugar_count3) # keyword21 22 # Configuration pattern23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order Large coffee with milk, 3 sugar(s))output Large coffee with milk, 3 sugar(s) === Configuration Pattern ===def print_report(title="Report", columns=2, show_header=False):
pass 1 of 337def print_report(titleReport="Report", columns2=2, show_headerFalse=FalseFalse):38 """Print a configurable report."""39 if show_header:All 3 passes — pass 1 is the card above pass titlecolumnsshow_header1 Report 2 False 2 Sales Report 3 False 3 Status 2 True else:
pass 1 of 239if show_header:40 print(f" === {title} ===")41else:42 print(f" {titleReport}")43print(f" ({columns} columns)")output Reportprint(f" ({columns} columns)")
23 print("\n=== Configuration Pattern ===")24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns2} columns)")output (2 columns)else:
pass 2 of 239if show_header:40 print(f" === {title} ===")41else:42 print(f" {titleSales Report}")43print(f" ({columns} columns)")output Sales Reportprint(f" ({columns} columns)")
24 print_report()25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns3} columns)")output (3 columns)if show_header:
38"""Print a configurable report."""39if show_headerTrue:40 print(f" === {titleStatus} ===")41else:output === Status ===print(f" ({columns} columns)")
25 print_report(title="Sales Report", columns=3)26 print_report(show_header=True, title="Status")2728def make_coffee(size="medium", milk=False, sugar=0):29 """Make coffee with customizable options."""30 order = f" {size.capitalize()} coffee"31 if milk:32 order += " with milk"33 if sugar > 0:34 order += f", {sugar} sugar(s)"35 print(order)3637def print_report(title="Report", columns=2, show_header=False):38 """Print a configurable report."""39 if show_header:40 print(f" === {title} ===")41 else:42 print(f" {title}")43 print(f" ({columns2} columns)")output (2 columns)main()
45if __name__ == "__main__":46 main()
All defaults must come after non-default parameters.
The mutable default trap
Never use mutable objects as defaults!
def main():
print("=== ⚠️ Mutable Default Trap ===\n")
# Watch carefully!
print("Calling add_item 3 times with defaults:")
result1 = add_item_broken("apple")
print(f"Call 1: {result1}")
result2 = add_item_broken("banana")
print(f"Call 2: {result2}") # Surprise!
result3 = add_item_broken("cherry")
print(f"Call 3: {result3}") # Even worse!
print("\n=== What Happened? ===")
print("Default list is created ONCE at function definition.")
print("Every call shares the SAME list object!")
print("Each append adds to that shared list.")
print("\n=== With Explicit Lists ===")
# These work because we provide our own lists
my_list = []
add_item_broken("dog", my_list)
print(f"My list: {my_list}")
other_list = []
add_item_broken("cat", other_list)
print(f"Other list: {other_list}")
print("\n=== Same Problem with Dict ===")
print(add_settings_broken("theme", "dark"))
print(add_settings_broken("volume", "100")) # Both settings!
# ❌ BROKEN: Mutable default
def add_item_broken(item, items=[]):
items.append(item)
return items
# ❌ BROKEN: Dict default
def add_settings_broken(key, value, settings={}):
settings[key] = value
return settings
if __name__ == "__main__":
main()
def main():
1def main():2 print("=== ⚠️ Mutable Default Trap ===\n")3 4 # Watch carefully! #?trap5 print("Calling add_item 3 times with defaults:")6 7 result1 = add_item_broken("apple")8 print(f"Call 1: {result1}")output=== ⚠️ Mutable Default Trap === Calling add_item 3 times with defaults:items ← ['apple']
pass 1 of 535# ❌ BROKEN: Mutable default #?broken36def add_item_broken(itemapple, items[]=[]):37 items→ ['apple'].append(itemapple)38 return items['apple']All 5 passes — pass 1 is the card above pass itemitems1 apple [] → ['apple'] 2 banana ['apple'] → ['apple', 'banana'] 3 cherry ['apple', 'banana'] → ['apple', 'banana', 'cherry'] 4 dog [] → ['dog'] 5 cat [] → ['cat'] result1 ← ['apple']
7result1→ ['apple'] = add_item_broken("apple")8print(f"Call 1: {result1['apple']}")910result2 = add_item_broken("banana")11print(f"Call 2: {result2}") # Surprise!outputCall 1: ['apple']result2 ← ['apple', 'banana']
10result2→ ['apple', 'banana'] = add_item_broken("banana")11print(f"Call 2: {result2['apple', 'banana']}") # Surprise!1213result3 = add_item_broken("cherry")14print(f"Call 3: {result3}") # Even worse!outputCall 2: ['apple', 'banana']result3 ← ['apple', 'banana', 'cherry'], my_list ← []
13result3→ ['apple', 'banana', 'cherry'] = add_item_broken("cherry")14print(f"Call 3: {result3['apple', 'banana', 'cherry']}") # Even worse!1516print("\n=== What Happened? ===") #?explain17print("Default list is created ONCE at function definition.")18print("Every call shares the SAME list object!")19print("Each append adds to that shared list.")2021print("\n=== With Explicit Lists ===")22# These work because we provide our own lists23my_list→ [] = []24add_item_broken("dog", my_list[])25print(f"My list: {my_list}")outputCall 3: ['apple', 'banana', 'cherry'] === What Happened? === Default list is created ONCE at function definition. Every call shares the SAME list object! Each append adds to that shared list. === With Explicit Lists ===my_list ← ['dog'], other_list ← []
23my_list = []24add_item_broken("dog", my_list→ ['dog'])25print(f"My list: {my_list['dog']}")2627other_list→ [] = [] #?explicit28add_item_broken("cat", other_list[])29print(f"Other list: {other_list}")outputMy list: ['dog']other_list ← ['cat']
27other_list = [] #?explicit28add_item_broken("cat", other_list→ ['cat'])29print(f"Other list: {other_list['cat']}")3031print("\n=== Same Problem with Dict ===")32print(add_settings_broken("theme", "dark"))33print(add_settings_broken("volume", "100")) # Both settings!outputOther list: ['cat'] === Same Problem with Dict ===settings[key] ← dark
pass 1 of 240# ❌ BROKEN: Dict default41def add_settings_broken(keytheme, valuedark, settings{}={}):42 settings[key]→ dark = valuedark43 return settings{'theme': 'dark'}print(add_settings_broken("theme", "dark"))
31print("\n=== Same Problem with Dict ===")32print(add_settings_broken("theme", "dark"))33print(add_settings_broken("volume", "100")) # Both settings!output{'theme': 'dark'}settings[key] ← 100
pass 2 of 240# ❌ BROKEN: Dict default41def add_settings_broken(keyvolume, value100, settings{'theme': 'dark'}={}):42 settings[key]→ 100 = value10043 return settings{'theme': 'dark', 'volume': '100'}print(add_settings_broken("volume", "100")) # Both settings!
32 print(add_settings_broken("theme", "dark"))33 print(add_settings_broken("volume", "100")) # Both settings!3435# ❌ BROKEN: Mutable default #?broken36def add_item_broken(item, items=[]):37 items.append(item)38 return items3940# ❌ BROKEN: Dict default41def add_settings_broken(key, value, settings={}):42 settings[key] = value43 return settings4445if __name__ == "__main__":46 main()47#@help trapoutput{'theme': 'dark', 'volume': '100'}
Defaults are evaluated once at definition time. Mutable defaults persist!
Use None to avoid the trap
The standard pattern to avoid mutable default issues.
def main():
print("=== None Pattern: Safe Defaults ===\n")
# Correct way with lists
print("Using None pattern:")
result1 = add_item("apple")
print(f"Call 1: {result1}")
result2 = add_item("banana")
print(f"Call 2: {result2}") # Fresh list!
result3 = add_item("cherry")
print(f"Call 3: {result3}") # Still fresh!
print("\n=== Providing Your Own List ===")
my_list = ["existing"]
result = add_item("new", my_list)
print(f"With my list: {result}")
print("\n=== Pattern Comparison ===")
print("❌ def func(items=[]): - Broken!")
print("✅ def func(items=None): - Safe!")
# Dictionary pattern
print("\n=== None Pattern with Dict ===")
config1 = build_config(debug=True)
print(f"Config 1: {config1}")
config2 = build_config(verbose=True)
print(f"Config 2: {config2}") # Independent!
# ✅ CORRECT: None default
def add_item(item, items=None):
if items is None:
items = [] # Fresh list each time!
items.append(item)
return items
# ✅ CORRECT: Dict with None
def build_config(base_config=None, **settings):
if base_config is None:
base_config = {} # Fresh dict each time!
base_config.update(settings)
return base_config
if __name__ == "__main__":
main()
def main():
1#@var=default,withDict2def main():3 print("=== None Pattern: Safe Defaults ===\n")4 5 # Correct way with lists #?correct6 print("Using None pattern:")7 8 result1 = add_item("apple")9 print(f"Call 1: {result1}")output=== None Pattern: Safe Defaults === Using None pattern:def add_item(item, items=None):
pass 1 of 434# ✅ CORRECT: None default #?none35def add_item(itemapple, itemsNone=NoneNone):36 if items is None:37 items = [] # Fresh list each time!All 4 passes — pass 1 is the card above pass itemitems1 apple None 2 banana None 3 cherry None 4 new ['existing'] → ['existing', 'new'] items ← []
pass 1 of 335def add_item(item, items=None):36 if itemsNone is None:37 items→ [] = [] # Fresh list each time!38 items.append(item)All 3 passes — pass 1 is the card above pass items1 None → [] 2 None → [] 3 None → [] items ← ['apple']
37 items = [] # Fresh list each time!38items→ ['apple'].append(itemapple)39return items['apple']result1 ← ['apple']
8result1→ ['apple'] = add_item("apple")9print(f"Call 1: {result1['apple']}")1011result2 = add_item("banana")12print(f"Call 2: {result2}") # Fresh list!outputCall 1: ['apple']items ← ['banana']
37 items = [] # Fresh list each time!38items→ ['banana'].append(itembanana)39return items['banana']result2 ← ['banana']
11result2→ ['banana'] = add_item("banana")12print(f"Call 2: {result2['banana']}") # Fresh list!1314result3 = add_item("cherry")15print(f"Call 3: {result3}") # Still fresh!outputCall 2: ['banana']items ← ['cherry']
37 items = [] # Fresh list each time!38items→ ['cherry'].append(itemcherry)39return items['cherry']result3 ← ['cherry'], my_list ← ['existing']
14result3→ ['cherry'] = add_item("cherry")15print(f"Call 3: {result3['cherry']}") # Still fresh!1617print("\n=== Providing Your Own List ===")18my_list→ ['existing'] = ["existing"] #?provide19result = add_item("new", my_list['existing'])20print(f"With my list: {result}")outputCall 3: ['cherry'] === Providing Your Own List ===my_list ← ['existing', 'new'], result ← ['existing', 'new']
18my_list = ["existing"] #?provide19result→ ['existing', 'new'] = add_item("new", my_list→ ['existing', 'new'])20print(f"With my list: {result['existing', 'new']}")2122print("\n=== Pattern Comparison ===")23print("❌ def func(items=[]): - Broken!")24print("✅ def func(items=None): - Safe!")2526# Dictionary pattern #@var=_,!27print("\n=== None Pattern with Dict ===")28config1 = build_config(debug=True)29print(f"Config 1: {config1}")outputWith my list: ['existing', 'new'] === Pattern Comparison === ❌ def func(items=[]): - Broken! ✅ def func(items=None): - Safe! === None Pattern with Dict ===def build_config(base_config=None, **settings): #?dict
pass 1 of 242# ✅ CORRECT: Dict with None43def build_config(base_configNone=NoneNone, **settings): #?dict44 if base_config is None:45 base_config = {} # Fresh dict each time!base_config ← {}
pass 1 of 243def build_config(base_config=None, **settings): #?dict44 if base_configNone is None:45 base_config→ {} = {} # Fresh dict each time!46 base_config.update(settings)base_config ← {'debug': True}
45 base_config = {} # Fresh dict each time!46 base_config→ {'debug': True}.update(settings{'debug': True})47 return base_config{'debug': True}48#@var=_,!config1 ← {'debug': True}
27print("\n=== None Pattern with Dict ===")28config1→ {'debug': True} = build_config(debug=True)29print(f"Config 1: {config1{'debug': True}}")3031config2 = build_config(verbose=True)32print(f"Config 2: {config2}") # Independent!outputConfig 1: {'debug': True}def build_config(base_config=None, **settings): #?dict
pass 2 of 242# ✅ CORRECT: Dict with None43def build_config(base_configNone=NoneNone, **settings): #?dict44 if base_config is None:45 base_config = {} # Fresh dict each time!base_config ← {}
pass 2 of 243def build_config(base_config=None, **settings): #?dict44 if base_configNone is None:45 base_config→ {} = {} # Fresh dict each time!46 base_config.update(settings)base_config ← {'verbose': True}
45 base_config = {} # Fresh dict each time!46 base_config→ {'verbose': True}.update(settings{'verbose': True})47 return base_config{'verbose': True}48#@var=_,!config2 ← {'verbose': True}
31 config2→ {'verbose': True} = build_config(verbose=True)32 print(f"Config 2: {config2{'verbose': True}}") # Independent!3334# ✅ CORRECT: None default #?none35def add_item(item, items=None):36 if items is None:37 items = [] # Fresh list each time!38 items.append(item)39 return items4041#@var=_,!42# ✅ CORRECT: Dict with None43def build_config(base_config=None, **settings): #?dict44 if base_config is None:45 base_config = {} # Fresh dict each time!46 base_config.update(settings)47 return base_config48#@var=_,!4950if __name__ == "__main__":51 main()52#@help correctoutputConfig 2: {'verbose': True}
Use None as default, then create the mutable object inside the function.
Exercise: sentinel.py
Explore sentinel objects for distinguishing None from 'not provided'