Repetitive Labor
The Archmage asks Hoppy to build 3 Defensive Towers around the workshop.
Hoppy waves his wand, sweating: "Build a Red Tower!" ... "Build a Blue Tower!" ... "Build a Green Tower!"
The Archmage shakes his head: "Young Architect, what if you need 100 towers? Don't do repetitive labor. Draw a Magic Blueprint instead."
Drawing the Blueprint (Defining a Function)
In Python, we use a Function as a blueprint. Once drawn, you can use it infinitely.
def build_tower(color):
print("Building a " + color + " tower...")
print("Complete!")
Key points:
def: Tells the workshop "I'm starting a blueprint".build_tower: The name of your blueprint.(color): The Slot (Parameter). Whether red or blue, the structure is the same; only the color changes.
Using the Blueprint (Calling a Function)
A blueprint alone does nothing. You must Activate it.
build_tower("Red") # Poof! A red tower appears.
build_tower("Blue") # Poof! A blue tower.
Your Mission
Create a function named cast_fireball.
Give it one parameter: power.
Inside the function, print a message: "Casting fireball with power " + str(power) + "!"
At the end, call the function 3 times with power 10, 50, and 100.
The content inside the blueprint (function body) must be indented (4 spaces). If not, it falls off the paper!
Suggested SolutionExpandCollapse
def cast_fireball(power):
# Remember to convert power to string for concatenation
print("Casting fireball with power " + str(power) + "!")
cast_fireball(10)
cast_fireball(50)
cast_fireball(100)Advanced TipsWant more? Click to expandClick to collapse
F. Bridge to Reality
- Magic Blueprint = Function Definition.
- Slot = Parameter.
- Activate = Function Call.
- DRY Principle: Programmers have a golden rule called "Don't Repeat Yourself". Functions are the best tool for DRY.