Skip to content
Advertisement

python turtle loop

I am trying to create a looping square, and cannot figure out how to get my code to allow me to keep repeating the command of creating squares, times the number input, heres what I have currently.

square_count = input("Enter the number of squares to draw: ")
count_int = int(square_ct)

if count_int > 1:

    turtle.begin_fill()
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.end_fill()

    turtle.up()
    turtle.forward(20)
    turtle.color(random.random(),random.random(), random.random())

Advertisement

Answer

You can use for i in range(count_int): to run a piece of code repeatedly given a repeat count in count_int:

if count_int > 1:
    for i in range(count_int):
        turtle.begin_fill()
        turtle.forward(100)
        turtle.right(90)
        turtle.forward(100)
        turtle.right(90)
        turtle.forward(100)
        turtle.right(90)
        turtle.forward(100)
        turtle.end_fill()

        turtle.up()
        turtle.forward(20)
        turtle.color(random.random(),random.random(), random.random())
Advertisement