Py学习  »  Python

Python不会在循环后销毁变量

markroxor • 5 年前 • 1564 次点击  

与其他语言(如c)不同,c++的变量范围保持在循环中。如。

for(int i=0; i<5; i++)
{
    do stuff;
}

i+=1  // raises error as i is not initialised.

for i in range(5)
    do stuff

i+=1  # doesn't raise error as i is initialised.

虽然这有时会有帮助,但有时会很痛苦,因为我很少使用变量名,比如 i, key, value 再一次在代码循环后没有面对任何显式错误。

有没有比使用 del i 循环后要避免上述问题吗?

Short description of the scoping rules? 我很久以前就见过了。该线程描述了范围界定在python中是如何工作的,而我的问题则完全不同。请将此取消标记为副本。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54251
 
1564 次点击  
文章 [ 1 ]  |  最新文章 5 年前
greentec
Reply   •   1 楼
greentec    6 年前

在Python3中,列表理解可能是一个答案。。。?

[print(i) for i in range(5)]
print(i)

>> 0
1
2
3
4

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-598b4fd0c0c5> in <module>()
1 [print(i) for i in range(5)]
----> 2 print(i)

NameError: name 'i' is not defined