首页 > 解决方案 > How would I loop the triangles/improve my code? (Nested triangle turtle)

问题描述

I am currently learning python with The Open University, I have created some code to draw a set of nested triangles decreasing in size every time they are drawn.

I am asked to incorporate two loops to achieve this, but silly me has done it in one.

How would I achieve the two loop goal whilst achieving the same result?

>>> from turtle import *
>>> trisize = 80
>>> for triangles in range(1, 5):
    forward(trisize)
    left(120)
    forward(trisize)
    left(120)
    forward(trisize)
    left(120)
    trisize - 20
    penup()
    forward(10)
    left(90)
    forward(5)
    right(90)
    pendown()
    trisize = trisize - 20

My expected result is four triangles nested inside of each other, I achieve this but without using two loops.

标签: pythonturtle-graphics

解决方案


我想我明白了,感谢目前正在尝试回答但尚未发表评论的任何人。这是我为任何需要它的人提供的解决方案。

while trisize >= 20:
    for sides in range(1, 4):
        forward(trisize)
        left(120)
    penup()
    forward(10)
    left(90)
    forward(5)
    right(90)
    pendown()
    trisize = trisize - 20

推荐阅读