Learning to Code: Art with Python Turtle

Loading...

Square one - draw a square!


from turtle import *

setheading(90)
forward(30)
right(90)
forward(30)
right(90)
forward(30)
right(90)
forward(30)

done()
          

Moving on to the next square

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.

Two more squares

If we paste the previously copied lines two more times, we get a total of four squares that look something like this:

four small squares in a square formation

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.

... and many many more!

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.

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()
          
flowers with three, five, and nine square petals

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?

Other things to try

See more at turtle documentation.