簡體   English   中英

關於烏龜函數中的for循環以及一般問題

[英]Question about for loops in turtle functions and also in general

一般關於for循環的問題:

我是 Python 的新手,想知道“for 循環”的目的是什么? 他們在函數中做了什么/他們生產了什么 output? 它們什么時候使用?

(我對什么是 for 循環進行了一些研究,但大多數來源都令人困惑/不清楚,所以我決定在這里提問。)

關於在 turtle 中使用 for 循環的問題:

處理填充形狀的 colors 的以下代碼中是否需要 for 循環 function? 我看到有些人在演示填充顏色的示例時使用它,但我不太確定它是否需要或它的作用。

# Example code: I know, nothing is shown 
# because I haven't told the function to draw anything, this is just an example.

t.pencolor("blue")
t.fillcolor("blue")
t.begin_fill()
for i in range(4):
    # remove 'pass' and write some code here, for loop is not doing any thing.
    pass
t.end_fill()

# I noticed that this code produced the same output as:

t.pencolor("blue")
t.fillcolor("blue")
t.begin_fill()
t.end_fill()

每當您需要一遍又一遍地做同樣的事情時,您就可以使用for循環(a)

例如(使用您關注的“烏龜”區域),假設您想畫一個圓(或近似圓的東西)。 你可以這樣做:

pen down
for i in 1..360:
    go forward 1 unit
    turn right one degree
pen up

另一種選擇是一個相當長的命令序列,形式如下:

    got forward 1 unit
    turn right one degree
    got forward 1 unit
    turn right one degree
    got forward 1 unit
    turn right one degree
    : :
    got forward 1 unit
    turn right one degree

沒有人想閱讀或調試:-)


(a)我教初學者的方式基本上是向他們介紹程序流的三個主要概念:

  • 順序,按順序做事;
  • 迭代,多次做類似的事情;
  • 選擇,根據條件做不同的事情。
for i in range(4):
  t.forward(150)
  t.right(90)

改變 range(1), range(2), range(3) 那么你將能夠看到 for 循環的美妙之處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM