简体   繁体   English

关于乌龟函数中的for循环以及一般问题

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

Question about for loops in general:一般关于for循环的问题:

I am new to Python was wondering what the purpose of "for loops" is?我是 Python 的新手,想知道“for 循环”的目的是什么? What do they do in a function/what output do they produce?他们在函数中做了什么/他们生产了什么 output? When are they used?它们什么时候使用?

(I've done some research on what a for loop is, but most sources are confusing/unclear so I decided to ask on here.) (我对什么是 for 循环进行了一些研究,但大多数来源都令人困惑/不清楚,所以我决定在这里提问。)

Question about using for loops in turtle:关于在 turtle 中使用 for 循环的问题:

Is the for loop function required in the following code dealing with filling in colors of a shape?处理填充形状的 colors 的以下代码中是否需要 for 循环 function? I've seen some people use it when demonstrating examples of filling in color, but I'm not quite sure if it's required or what it does.我看到有些人在演示填充颜色的示例时使用它,但我不太确定它是否需要或它的作用。

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

You use a for loop whenever you need to do the same thing over and over (a) .每当您需要一遍又一遍地做同样的事情时,您就可以使用for循环(a)

For example (using your "turtle" area of concern), say you wanted to draw a circle (or something approximating a circle).例如(使用您关注的“乌龟”区域),假设您想画一个圆(或近似圆的东西)。 You could do this with something like:你可以这样做:

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

The alternative would be a rather long sequence of commands of the form:另一种选择是一个相当长的命令序列,形式如下:

    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

which nobody wants to read or debug:-)没有人想阅读或调试:-)


(a) The way I teach beginners is to basically introduce them to the three main concepts of program flow: (a)我教初学者的方式基本上是向他们介绍程序流的三个主要概念:

  • sequence, doing things sequentially in order;顺序,按顺序做事;
  • iteration, doing a similar thing many times;迭代,多次做类似的事情; and
  • selection, doing different things based on conditions.选择,根据条件做不同的事情。
for i in range(4):
  t.forward(150)
  t.right(90)

change range(1), range(2), range(3) then you will be able to see beauty of for loop.改变 range(1), range(2), range(3) 那么你将能够看到 for 循环的美妙之处。

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

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