【问题标题】:python turtle looppython乌龟循环
【发布时间】:2012-09-08 14:52:36
【问题描述】:

我正在尝试创建一个循环方块,但无法弄清楚如何让我的代码允许我继续重复创建方块的命令,乘以数字输入,这就是我目前所拥有的。

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())

【问题讨论】:

    标签: python loops for-loop turtle-graphics


    【解决方案1】:

    您可以使用for i in range(count_int): 重复运行一段代码,并在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())
    

    【讨论】:

    • turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) 是重复多次的相同值,有没有更好的写法?
    • @DebRaj:请参阅Python 3: Can we avoid repeating an instance name when calling several of its methods?,这可能是您首先发表评论的原因。
    • @Martin Pieters 该链接是关于各种运动的。我希望它具有类似的运动声誉。我发现定义一个方法很有帮助:def draw_square(some_draw): for i in range (0, 4): some_draw.forward(100) some_draw.right(90) 然后将其称为draw_square(my_drawing_name) 就可以了。
    【解决方案2】:

    你可以试试这个

    x=1
    while x < 10000000:
    

    当您执行此操作时,您在此之后键入的任何内容都将再次执行,直到已完成 10000000 次。 最后,虽然你必须把它放进去。

    x+=1
    

    这是我做的例子。

    import turtle
    bob = turtle.Turtle()
    wn = turtle.Screen()
    bob.color("white")
    bob.speed(1000000000000000000000000)
    wn.bgcolor("black")
    x=1
    while x < 10000000:
    bob.forward(90)
    bob.left(89)
    bob.forward(1+x)
    

    【讨论】:

      【解决方案3】:

      再一次,你可以把它放在一个函数中并告诉它再次运行自己

      def example():
          [insert code]
          example()
      

      【讨论】:

      • 你建议如何防止它无限执行?
      猜你喜欢
      • 1970-01-01
      • 2014-09-08
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多