The Wisdom of Laziness
The Archmage has a new task: Summon 50 Goblins to carry cargo.
Hoppy notices that 90% of Goblins are Green, and only a few captains are Red. But the old blueprint requires a color every time, so Hoppy has to write "Green" 45 times.
"Too tedious!" Hoppy complains. "Can't the blueprint just make Green ones by default?"
Factory Settings (Default Arguments)
Yes! We can install a Default Value into the blueprint slot.
def summon_goblin(color="Green"):
print("Summoned a " + color + " Goblin!")
Now the rules have changed:
- Empty: Automatically uses the default
"Green". - Filled: Overrides the default with your specific color.
Your Mission
Modify the make_potion function. Add a default value "Healing" to the effect parameter.
Call make_potion() without arguments. It should make a Healing potion.
Call make_potion("Poison") with an argument. It should make a Poison potion.
If you have multiple parameters, parameters with defaults must come LAST! Otherwise, Python gets confused about which value goes where.
Suggested SolutionExpandCollapse
def make_potion(effect="Healing"):
print("Brewed a potion with effect: " + effect)
make_potion() # Defaults to Healing
make_potion("Poison") # Overrides to PoisonAdvanced TipsWant more? Click to expandClick to collapse
F. Bridge to Reality
- Factory Setting = Default Argument.
- This is common in APIs. For example,
print()has a default argumentend='\n', which is why it adds a new line automatically. If you writeprint("Hi", end=""), it won't add a new line!