簡體   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