E2. Adding Color to Functions
🎯 Learning Goals
By the end of this lesson, you'll be able to:
- ○ You can add
colora parameter to a function - ○ You can draw color-filled bars with a function
Review: The Bar Drawing Function
Remember the draw_bar() function you made before?
def draw_bar(t, height, width=40):
"""A function that draws a bar"""
for _ in range(2):
t.forward(height)
t.right(90)
t.forward(width)
t.right(90)
Let's add a color featureto this function!
Step-by-Step: Adding Color
Step 1: Add a parameter
💡 Parameter order
t: the turtleheight: bar heightcolor: bar color (newly added!)width: bar width (default 40)
Step 2: Add the color code inside the function
def draw_bar(t, height, color, width=40):
t.fillcolor(color) # 1. Set the color
t.begin_fill() # 2. Start filling
for _ in range(2):
t.forward(height)
t.right(90)
t.forward(width)
t.right(90)
t.end_fill() # 3. Finish filling
Step 3: Call the function
Full Code Example
import turtle
def draw_bar(t, height, color, width=40):
"""A function that draws a color-filled bar"""
t.fillcolor(color)
t.begin_fill()
for _ in range(2):
t.forward(height)
t.right(90)
t.forward(width)
t.right(90)
t.end_fill()
# Main code
t = turtle.Turtle()
t.shape("turtle")
t.speed(3)
t.penup()
t.goto(-50, -100)
t.pendown()
t.left(90)
# Draw a blue bar!
draw_bar(t, 80, "blue")
Code Comparison
Function Without Color vs. Function With Color
| No color | With color |
|---|---|
def draw_bar(t, height, width=40): |
def draw_bar(t, height, color, width=40): |
t.fillcolor(color) |
|
t.begin_fill() |
|
for _ in range(2): |
for _ in range(2): |
t.forward(height) |
t.forward(height) |
t.right(90) |
t.right(90) |
t.forward(width) |
t.forward(width) |
t.right(90) |
t.right(90) |
t.end_fill() |
💡 What was added
- To the parameters
colorAdd - At the start of the function
fillcolor(),begin_fill()Add - At the end of the function
end_fill()Add
🎯 Mission: Make It Along
Mission 1: Draw a blue bar
Run the code to see the blue bar!
Mission 2: Change the color and height
draw_bar() Change the color and height in the call!
Example Answer
Mission 3: Complete the function
Fill in the blanks to complete the color function!
🎯 Quiz
Quiz: Calling a Function
draw_bar(t, 100, "red")what kind of bar does it draw?
Show Answer
Answer: B) Height 100, red
Color function practice:
- Add a parameter:
def draw_bar(t, height,, width=40): - Set the color:
t.fillcolor() - Call a function:
draw_bar(t, 80,)
🧩 Key Takeaways
What you learned in this lesson:
| Concept | Description |
|---|---|
| Add a parameter | def draw_bar(t, height, color): |
| Use the color | t.fillcolor(color) - Use the parameter! |
| Function call | draw_bar(t, 80, "blue") |
Preview of the Next Lesson
In the next lesson, we'll learn multiple colored barsLet's draw!