pythonturtle-graphicspython-turtle

Drawing staircases in a loop but not getting correct results


I am trying to draw 7 staircases with a loop but I have missed something and not sure why it's not working. It draws the first staircase and then goes completely off track and doesn't put the pen back down and I'm not sure why.

#Draw stairs 7 times
from turtle import*

#Stair repeat
for i in range (3):
    forward (25)
    left (90)
    forward(25)
    right(90)

#move to next stair
for i in range(7):
    penup()
    forward(25)
    right(90)
    forward(75)
    left(90)
    pendown()

My understanding is that the for loop would repeat the code, so if I want it to move for 7 separate stairs then the range is 7? This is obviously not correct though as it doesn't work. Hoping someone could point me in the correct direction as to why it's wrong.


Solution

  • A couple things seem amiss:

    Beyond that, avoid from turtle import *. This is confusing and can lead to bugs, because it brings hundreds of functions into your namespace, creating potential name clashes and making it hard to tell which functions are yours and which belong to the turtle module. Better to import turtle or from turtle import Screen, Turtle and create a turtle instance.

    Here's a rework that hopefully matches your intended result:

    import turtle
    
    t = turtle.Turtle()
    step_size = 25
    
    for _ in range(7):
        t.left(90)
        t.forward(step_size)
        t.right(90)
        t.forward(step_size)
    
    turtle.exitonclick()
    

    Based on the follow-up comment, if you want to draw staircases of 3 stairs 7 times, then nest your loops and add some code to reposition the turtle to wherever it needs to be to draw each staircase. For example:

    import turtle
    
    t = turtle.Turtle()
    step_size = 25
    
    for i in range(7):
        t.penup()
    
        # whatever logic puts you in the right position for the next stair
        t.goto(-step_size * i, 1.5 * step_size * i)
    
        t.pendown()
    
        for _ in range(3):
            t.left(90)
            t.forward(step_size)
            t.right(90)
            t.forward(step_size)
    
    turtle.exitonclick()
    

    I don't know what your expected goal is, so you'll need to adjust this to match that, but the general approach should be the same.