# Turtle Graphics : Repeating Squares Question

2408 views
4

In this code I was suppose to repeat a 100 squares inside of a square.

``````import turtle

num_squares = 100

turtle.pendown()
side = side_unit = 5

for sq in range(1, num_squares + 1):
turtle.left(90)
turtle.forward(side)
turtle.left(90)
turtle.forward(side)
turtle.left(90)
turtle.forward(side)
turtle.left(90)
side = side_unit + 3 * sq

turtle.goto(0,0)

turtle.done()
``````

I got it to work but I'm having trouble understanding why it works regarding the line side = side_unit + 3 * sq . Why would multiplying side_unit + 3 * sq make a new square?

13

To make this simpler to understand I would define a function for drawing a single square.

``````def draw_square(side_length):
""" Draw a square with given side length and return to origin """
for i in range(4):
turtle.left(90)
turtle.forward(side_length)
turtle.left(90)
turtle.goto(0, 0)
``````

that simplifies the loop to:

``````for sq in range(1, num_squares + 1):
draw_square(side)
side = side_unit + 3 * sq
``````

A square with side length `side` is drawn every loop. since `sq` increments by 1 every time the loop iterates, `side_unit + 3 * sq` gets 3 larger every iteration. You are setting `side` (which is the square's side length) to this, which means that the square's side length will increase by 3 every iteration.

posted this