"from math import sqrt" 有效,但 "import math" 无效。是什么原因?

"from math import sqrt" works but "import math" does not work. What is the reason?

我是编程新手,刚刚学习 python。

我正在使用 Komodo Edit 9.0 编写代码。所以,当我写 "from math import sqrt" 时,我可以毫无问题地使用 "sqrt" 函数。但是如果我只写 "import math",那么那个模块的 "sqrt" 功能就不起作用了。这背后的原因是什么?我能以某种方式修复它吗?

你有两个选择:

import math
math.sqrt()

会将 math 模块导入到它自己的命名空间中。这意味着函数名称必须以 math 为前缀。这是一个很好的做法,因为它避免了冲突并且不会覆盖已经导入到当前命名空间的函数。

或者:

from math import *
sqrt()

会将 math 模块中的所有内容导入当前命名空间。 That can be problematic.

当您只使用 import math 时,sqrt 函数会以不同的名称出现:math.sqrt

如果你只import math调用sqrt函数你需要这样做:

In [1]: import math

In [2]: x = 2

In [3]: math.sqrt(x)
Out[3]: 1.4142135623730951

这是因为from math import sqrt给你带来了sqrt功能,而import math只给你带来了模块。

如果您需要平方根,您也可以将一个数乘以 0.5 取幂。

144 ** 0.5

给出结果:

12.0

如果命令 Import math 多次出现,您将收到错误消息:UnboundLocalError: local variable 'math' referenced before assignment