我偶然发现了另一个我在 Python 中遗漏的基本概念:
有了这个基本的 for
(foreach) 循环:
x = 15
for x in range(10):
continue
print(x)
我预计 x
的值为 15,但我得到的却是 9。
C 中的相同代码片段返回 x
的原始值 – 15:
#include <stdio.h>
int main(void)
{
int x = 15;
for (int x = 0; x < 10; x++)
{
continue;
}
printf("%d", x);
return 0;
}
我不知道变量范围在这里是如何工作的。
既然 x
是在 for
循环范围外声明的,难道不应该在循环的生命周期内创建一个新的局部变量吗?
为什么 x
在 Python 版本中被覆盖了?
最佳答案
这不一样。在 C 中,您显式创建一个新变量,而在 Python 中,您在 for
范围内重用该名称,最终覆盖之前的值。
所以 C 等价物实际上是:
#include <stdio.h>
int main(void)
{
int x = 15;
for (x = 0; x < 10; ++x)
{
continue;
}
--x; // To accommodate the different behavior of the range loop
printf("%d", x);
return 0;
}
不要忘记,在 Python 中,变量只是动态创建的字典中的条目,而在 C 中,它们是独立的静态项。
关于python - For循环覆盖外部变量而不是创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356539/