【问题标题】:"from math import sqrt" works but "import math" does not work. What is the reason?“from math import sqrt”有效,但“import math”无效。是什么原因?
【发布时间】:2015-06-04 14:29:11
【问题描述】:

我是编程新手,刚学python。

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

【问题讨论】:

  • 您没有使用math.sqrt()访问上述方法。
  • 你需要使用math.sqr
  • 我可能会在 15 分钟后接受答复。好的,我会这样做的。谢谢。 @随机用户名
  • FWIW,如果你只想做平方根,不要费心导入sqrt。而不是 sqrt(x) 只需执行 x ** 0.5 - 内置的幂运算符是高效的并节省了函数调用。
  • 不,我只是想了解模块的工作原理。无论如何,谢谢你的好意建议。 @PM2Ring

标签: python module komodo


【解决方案1】:

你有两个选择:

import math
math.sqrt()

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

或者:

from math import *
sqrt()

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

【讨论】:

  • 但是,在普通脚本中进行星号导入通常不是一个好主意。见Why is “import *” bad?
  • 我可以使用“from module_name import func1, func2, func3, ...”等代替*。我想这样会更好。
  • @SheikhAhmadShah 是的,但您仍然可能会意外覆盖现有函数。
  • 你也可以做 from math import sqrtfrom math import sqrt as square_root_function 所以我猜这使得 4 选项
【解决方案2】:

如果你只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 只给你带来了模块。

【讨论】:

  • @Maverick 也许你在想 2^2?
  • @meepi 我真的很困惑,因为我从未注意到这个结果。理想情况下,平方根应该是 2**2 = 4,这就是你期望在 math.sqrt(2) 中返回的结果。你能解释一下吗?
  • @Maverick 您正在考虑平方,而不是平方根。 squared 是一个指数,如 2**2 = 42**3 = 8。平方根是a number that produces a specified quantity when multiplied by itself.1.4142135623730951 * 1.4142135623730951 ≈ 2
  • 2^2 或 4^4 会导致什么结果?我来到这篇文章寻找两个坐标(纬度,经度)之间的距离,并且在他们编写 sqrt 的所有这些公式中,所以不知道使用什么来获得正确的结果。
  • @Maverick 2^2 是公正的,而 4^4 只是指数的符号。它们与2**2 is just 和4**4 相同。计算地球上 2 个坐标之间的距离使用 Haversine 公式,该公式确实使用平方根
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    144 ** 0.5
    

    给出结果:

    12.0
    

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2017-05-29
        • 2019-06-07
        • 1970-01-01
        • 2021-05-09
        • 2019-08-22
        • 1970-01-01
        • 2021-11-01
        • 2014-05-16
        • 2021-01-12
        相关资源
        最近更新 更多