python问题记录

今天才python群里看到一个问题

python2.7:

  

  L = [x for x in 'hello']

  
print L
  
print x

python3.4:

  

  L = [ x for x in 'hello' ] 
  print (L)   print (x)

两者都可以打印出

    L = ['h', 'e', 'l', 'l', 'o']

但是只有python2.7可以打印出变量x的值: 

   x = 'o'

  

   >>> L = [x for x in 'hello']
  >>> print L
  ['h', 'e', 'l', 'l', 'o']
  >>> print x
  o
  >>> 

python3.4中则显示x变量没有定义

  

  >>> L = [x for x in 'hello']
  >>> print (L)
  ['h', 'e', 'l', 'l', 'o']
  >>> print (x)
  Traceback (most recent call last):
    File "<pyshell#2>", line 1, in <module>
      print (x)
  NameError: name 'x' is not defined
  >>> 

就是这么一个问题,我通过pycharm单步调试了一下,发现python2.7执行完列表解析语句后,变量x任然存在。

而在python3.4中,执行完列表解析后,变量x则消失了。

下面贴出我用pycharm分别在不同环境下调试的结果

python2.7:

python3.4:

我想这可能是python3.4基于安全考虑,避免变量占用内存的情况。

另一方面,也保证了在后面使用变量的情况下不会出现错用变量的现象。

2016-03-28     13:26:34

原文地址:https://www.cnblogs.com/xautxuqiang/p/5328700.html