[英]Question about for loops in turtle functions and also in general
我是 Python 的新手,想知道“for 循环”的目的是什么? 他们在函数中做了什么/他们生产了什么 output? 它们什么时候使用?
(我对什么是 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.