繁体   English   中英

如何在Turtle Graphics Python中打破无限循环

[英]How to Break Infinite Loop in Turtle Graphics Python

我为完成任务所需的任务编写了代码。 这是根据用户输入绘制多边形的形状,并按指定的边数绘制形状的数量。 唯一的问题是,绘制形状后,箭头将无限循环地不断跟踪。 我尝试在最后使用break,但是没有用。

 from turtle import *

def polygon(n, length):
    Screen()
    shape('turtle')
    mode('logo')

n = input ("Enter number of sides ")
print ("you entered ", n) 
length = input("Enter the length of sides ")
print ("you entered ", length)
n=int(n)
length=int(length)


for side in range(n):
    forward(length)
    right(360/n)
    while side in range(n):
        right(360/n)
        for side in range(n):
            forward(length)
            right(360/n)

到目前为止,我在技术上可以完成该任务,但是最后的无限循环使我很烦。

主要问题是while循环持续了无数时间。

#This is infinite loop because 'side' iterator is ALWAYS in the sequence returned from range function
while side in range(n):

同样,使用代码的当前结构,该函数不会执行任何操作,只会浪费空间(您可以从可以理解的shell调用它)。 我们还有其他一些冗余之处。 让我们设计您的脚本,以便可以从您创建的函数控制海龟的多边形。 希望您会看到结合使用递归和正确使用函数时,turtle模块有多么强大。

让我们看一下多边形函数1st的声明。 我觉得您的脚本除了自然的方便性外,还应该围绕多边形函数旋转,这是由于脚本中包含的参数所致。 尽管根据脚本的隐含设计,它们不是必需的(这里至少是),但包含它们意味着A:您打算使用此功能来控制乌龟,或者B:您不太了解功能/参数的工作原理。 为了提供更多的学习经验,无论哪种情况,我们都绝对应该将脚本集中在该函数上。

def polygon(n,length): #<--- get ride of 'n' & 'length' parameters
def polygon(n=None,length=None): #<---These are defualt values if you wish to go with that direction
def polygon(): #<---This is the declaration I'll follow for aiding your script

现在摆脱参数。 稍后,我们将它们带回嵌套函数中。 接下来,我们将其余脚本添加到多边形函数中。 因为您的n和length变量收集输入,所以它使面函数的参数无效。 它既不是“场景”也不是“场景”,如果需要,您可以同时具有一些控制流。 在将脚本添加到多边形函数之前,我想指出一下如何两次声明变量,这是第二次将变量转换为整数。 Python允许我们在第一次声明它们时将它们嵌套在int()函数中。

n = input("Enter num ")
n = int(n) #<---instead of these 1st 2 lines, do the 3rd line below.
n = int(input("Enter num: ")) #<--1 line of code that is equally as readable as 2.

修改完n和length变量后,让我们将所有内容添加到我们的多边形函数中(while循环除外,摆脱与之相关的所有内容)。 请注意,屏幕,形状和模式功能已移至变量声明下方。 这样,在用户向程序中输入信息时,乌龟窗口就不会跳到用户面前。

def polygon():
    n = int(input("Enter number of sides: "))
    print("You entered %d sides.\n"%(n))
    length = int(input("Enter length of sides: "))
    print("Your sides are %d pixels long.\n"%(length))
    Screen()
    shape('turtle')
    mode('logo')

现在,我们有了一个清晰易读的功能,可以通过创建多边形来处理我们的业务。 为此,我们将使用同时使用递归和参数的嵌套函数。 我们将其称为“循环播放器”。 原因是您的任务是制作等边的多边形(换句话说,多边形数== n)。 Looper将为我们实现这一目标。 第一,它将在多边形中建立的变量作为参数。 然后,我们将在内部使用您以前的for循环。

def looper(n,length,loops=n): #notice the 'loops=n' default parameter, this allows to keep track of it recursively
    if (loops > 0): #As long as loops is greater than zero this functin will repeat itself as many times as 'n'
        for side in range(n):
            forward(length)
            right(360/n)
        penup()
        #penup after the forloop so that the turtle will not draw while searching for next polygon space
        setposition(xcor()+length,ycor()+length) #xcor() and ycor() return the current position of the turtle
        #notice that we add it to the length of of our sides, this is how the turtle will space out the polys.
        #I would even experiment with things like setposition(xcor()+(length*2),ycor()+(length*2))
        pendown() #after turtle find the position we we use pendown() to prepare to draw again
        loops -= 1 #this decrements the loops parameter so that the functin will not call itself infinitely
        #(stack overflow)
        looper(n,length,loops) #recursively call our looper function again
        return #I personally always return the end of recursive functions to be safe, this may be redundant

本质上,递归是指函数在自身内部重复调用自身以执行任务。 为了确保它最终结束,我们告诉程序:“在函数执行其职责后,再绘制多边形,如果有任何循环”,我们告诉它“将循环减1”,以确保循环最终为零。 这和return语句(大致相当于您所说的“ break”)将向我们保证,我们不会无限次执行任务。 这段代码的最后一步是确保您实际上调用了多边形函数,因此您的代码将运行AND并出于相同的原因也调用looper(n,length)和多边形函数的结尾。

您的代码应如下所示:

from turtle import *

def polygon():
    n = int(input("Enter number of sides: "))
    print("You entered %d sides.\n"%(n))
    length = int(input("Enter length of sides: "))
    print("Your sides are %d pixels long.\n"%(length))
    Screen()
    shape('turtle')
    mode('logo')
    def looper(n,length,loops=n):
        if (loops > 0):
            for side in range(n):
            forward(length)
            right(360/n)
            penup()
            setposition(xcor()+length,ycor()+length)
            pendown()
            loops -= 1
            looper(n,length,loops)
            return
    looper(n,length)


polygon()

我几乎为您完成了任务,但是如果您学到了一两件事,那么我的目标就可以实现。 希望我能帮到我!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM