from turtle import *
setheading(90)
forward(30)
right(90)
forward(30)
right(90)
forward(30)
right(90)
forward(30)
done()
Change the number inside the first forward()
call to 40. Then copy lines 4 through 10 and add it to the bottom of your code, before the done()
statement. You should now have two squares.
If we paste the previously copied lines two more times, we get a total of four squares that look something like this:
Currently, we have a lot of repetitive code. We can simplify repititions using loops.
from turtle import *
setheading(90)
for i in range(4):
forward(40)
right(90)
forward(30)
right(90)
forward(30)
right(90)
forward(30)
done()
We can actually further simplify our code with another loop. Hint: you can put a loop inside a loop.
from turtle import *
setheading(90)
for i in range(4):
forward(40)
for j in range(3):
right(90)
forward(30)
done()
First, let's make our squares bigger. Replace the number passed to the forward()
call in the outer loop with 60, and that in the inner loop with 40. Next, let's make our turtle draw a faster by adding the line speed(10)
before our loop.
The challenge here is to draw lots of squares around in a circle. Try drawing 5 sets of our four squares from the previous step, each time turning to the right by 72 degrees. Hint: we need another loop.
from turtle import *
setheading(90)
speed(10)
for n in range(5):
left(72)
for i in range(4):
forward(60)
for j in range(3):
right(90)
forward(40)
done()
What if we wanted to create 2 more "flowers" next to the current one, but one of them with 3 petals and another with 9? Copy the code, lines 5 through 11 to repeat the task of drawing flowers then change the petal (and angle) numbers accordingly.
To space out my flowers, add the following lines of code before the loops that create the flowers, replacing the x, y inside each of the goto()
calls with
, respectively. (These are just coordinates that work well within the boundaries of our canvas inside trinket.)
penup()
goto(x, y)
pendown()
To be to create many "flowers", each time with a different number of petals, I can define a function to simplify my code.
def drawFlower(petals):
for n in range(petals):
left(360 / petals)
for i in range(4):
forward(60)
for j in range(3):
right(90)
forward(40)
Now replace the repetitive code with a call to our function named drawFlower
, and pass (input) the number of petals we want. For example, to draw a flower with three petals, write drawFlower(3)
. Note that 360 should be divisible by the number of petals.
Can you think of other ways we can simplify or add more flexibility to our code?
pencolor("blue")
, for example, or pencolor(r, g, b)
for some rgb values you can pick.width(5)
.begin_fill()
and end_fill()
.See more at turtle documentation.