python - 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。
解决方案
环境:
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
通配符导入)。
推荐阅读
- regex - 使用正则表达式提取器从 jmeter 中的 url 中提取值
- typescript - 打字稿没有重复值
- asp.net-mvc - 在本地主机中成功发送邮件,但在 [Somee, GoDaddy] 等实时服务器上发布时发送邮件失败
- amazon-web-services - 我们如何使用 saltstack 创建目录\文件夹用户 s3 存储桶
- python - 从用户输入中查找最小总和(不使用函数、lambda、map 等)
- yocto - 如何在 bitbake 中查找图像的配方文件顺序
- product - Magento 2中类别页面的分层导航中类别和属性过滤器的产品计数差异
- java - 带字符串的 switch 中需要的常量表达式
- sql - 如何为每个组生成汇总统计数据并转置?
- python - 打印 .triad_census() 会导致 TypeError