在python中循环结束后记住循环变量

2024-03-28 13:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

def john():
    for i in range(5):
        if i == 3:
            break
    print(i)

john()

上面的函数在调用时打印3,这是什么意思?循环结束/中断“ed”后,循环变量还记得吗?你知道吗


Tags: 函数inforifdefrangejohnprint
1条回答
网友
1楼 · 发布于 2024-03-28 13:10:12

For-loop variable scope

Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.

如果序列为空,则循环根本不会为变量赋值:

>>> for x in []:
        pass

>>> print(x)
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    print(x)
NameError: name 'x' is not defined

相关问题 更多 >