Accessing tuple with turtle on python

Question:

I’m still new to python and programming in general and it’s my first post here. I’m trying to draw a "house" shape with an X inside of it. I need to utilize a loop with a list that contains tuples which would be forward,left respectively. I figured what coordinates I would need to draw the house but I can’t utilize them to make the turtle move. It’s a school assignment. I’m attaching everything I got so far. Any insights would be highly appreciated, thank you so much!

def drawhouse(t, ls):
    fwd, lt = ls
    for fwd, lt in ls:
        t.forward(fwd)
        t.left(lt)


def main():
    import turtle
    wn = turtle.Screen()
    t = turtle.Turtle()
    wn.bgcolor("Cyan")
    wn.title("Drawing a house")
    wn.mainloop()
    ls = [(100, 90), (100, 90), (100, 240), (100, 240),
          (100, 285), (140, 225), (100, 225), (100, 0)]
    drawhouse(t, ls)


main()

Hope that the formatting for the code is right(seems to be on the preview) Thanks in advance.

Asked By: oMendigoPadeiro

||

Answers:

wn.mainloop() has to go at the bottom; no code after that point is executed until you close the window. So, put that at the bottom of your main() function.

Also, your drawhouse function needs a small change. You have fwd, lt = ls at the beginning, which causes an error. That syntax only works if there’s the same amount of values on the right as on the left (otherwise you’ll get a "too many values to unpack" error). Since ls contains more than 2 items, you’ll get this error. Also, since you’re setting fwd and lt in the loop, there’s no need to create or initialize those variables beforehand anyway:

for fwd, lt in ls:
    t.forward(fwd)
    t.left(lt)

And that’s it; your code works great after just making these two small changes:

def drawhouse(t, ls):
    for fwd, lt in ls:
        t.forward(fwd)
        t.left(lt)


def main():
    import turtle
    wn = turtle.Screen()
    t = turtle.Turtle()
    wn.bgcolor("Cyan")
    wn.title("Drawing a house")
    ls = [(100, 90), (100, 90), (100, 240), (100, 240),
          (100, 285), (140, 225), (100, 225), (100, 0)]
    drawhouse(t, ls)
    wn.mainloop()

main()
Answered By: Random Davis