Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing tuple with turtle on python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading