代码之家  ›  专栏  ›  技术社区  ›  markroxor

Python不会在循环后销毁变量

  •  0
  • markroxor  · 技术社区  · 7 年前

    与其他语言(如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中是如何工作的,而我的问题则完全不同。请将此取消标记为副本。

    1 回复  |  直到 7 年前
        1
  •  0
  •   greentec    7 年前

    在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