我是Python的新手,我想知道“ for循环”的目的是什么?它们在函数中做什么/产生什么输出?什么时候使用?
(我已经研究了for循环是什么,但是大多数资源令人困惑/不清楚,所以我决定在这里询问。)
以下代码中需要for循环函数来处理形状的颜色吗?我已经看到有人在演示填充颜色的示例时使用它,但是我不确定是否需要它或做什么。
# 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()
答案 0 :(得分:0)
只要需要一遍又一遍(a)做相同的事情,就使用for
循环。
例如(使用您关注的“乌龟”区域),您说要绘制一个圆(或近似圆的东西)。您可以使用类似的方法做到这一点:
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)我教初学者的方法是基本上向他们介绍程序流程的三个主要概念:
答案 1 :(得分:0)
for i in range(4):
t.forward(150)
t.right(90)
更改range(1),range(2),range(3),然后您将可以看到for循环的美妙之处。