首页 > 解决方案 > Python中常量'e'的奇怪行为

问题描述

我在 Python 中经历了非常奇怪的行为。我是一名电子工程师。所以我有时在等式中使用常数'e'。

from math import *

try:
    eval('print(log(e))')
except Exception as e:
    print(e)

try:
    eval('print(long(e))')
except Exception as e:
    print(e)

try:
    eval('log(e)')
except Exception as e:
    print(e)

输出是

1.0
name 'long' is not defined
name 'e' is not defined

我想念输入 log(e) 到 long(e)。在该方程之前 log(e) 运行良好,但在 long(e) 之后的第二个 log(e),Python 不理解“e”。

你知道那里发生了什么吗?

我在 Windows 上使用 python3.8.2。

标签: python

解决方案


环境:

except Exception as e:

从 中隐藏导入的名称math,但except输入块时(即抛出错误)。该引用在块外被清除,except但这会删除e. 它相当于:

>>> from math import e
>>> e
2.718281828459045
>>> e = "foo"  # shadow the imported name
>>> e
'foo'
>>> del e  # try to return to previous value
>>> e
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'e' is not defined

声明的文档中也提到了这一点try(强调我的):

当使用 分配了异常时as target它会在 except 子句的末尾被清除。这仿佛

except E as N:
    foo

被翻译成

except E as N:
    try:
        foo
    finally:
        del N

最简单的修复是:

  • 将异常重命名为e; 或者
  • import math然后参考(注意PEP-0008 不鼓励math.e通配符导入)。

推荐阅读