【发布时间】:2017-10-16 16:26:06
【问题描述】:
考虑这段代码:
import turtle
import sys
# function that draws a square using turtle graphics:
def drawSquare(t, sz): # t is a turtle object and sz is the size of the square
for i in range(4):
t.forward(sz)
t.left(90)
def main():
sys.setExecutionLimit(300000)
wn = turtle.Screen() # setting up the window
wn.bgcolor('lightgreen')
alex = turtle.Turtle() # setting up the turtle object
alex.color('blue')
alex.speed(10)
for i in range(24): # drawing the shape
drawSquare(alex, 100)
alex.right(15)
wn.exitonclick()
main()
在最后一个 for 循环中,我使用 i 作为循环变量。但在 for 循环中,我还调用了 drawSquare() 函数,该函数还包含一个带有名为 i 的循环变量的 for 循环。
当我运行这个程序时,它给出的输出与我将两个循环变量之一的名称更改为 counter 时的输出相同。这只是巧合,还是您可以将一个 for 循环嵌套在另一个循环中,并且它们具有相同的循环变量?
提前致谢。
【问题讨论】:
-
iindrawScope是它自己的世界(范围)中的不同对象 -
我认为当你调用一个函数时,这个函数有它自己的命名空间范围。所以这些变量在不同的范围内。
标签: python python-3.x loops for-loop turtle-graphics