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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30646650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:44:57  来源:igfitidea点击:

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

pythonmodulekomodo

提问by Sheikh Ahmad Shah

I am pretty new in programming, just learning python.

我在编程方面很新,刚刚学习python。

I'm using Komodo Edit 9.0 to write codes. So, when I write "from math import sqrt", I can use the "sqrt" function without any problem. But if I only write "import math", then "sqrt" function of that module doesn't work. What is the reason behind this? Can I fix it somehow?

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

采纳答案by fenceop

You have two options:

您有两个选择:

import math
math.sqrt()

will import the mathmodule into its own namespace. This means that function names have to be prefixed with math. This is good practice because it avoids conflicts and won't overwrite a function that was already imported into the current namespace.

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

Alternatively:

或者:

from math import *
sqrt()

will import everything from the mathmodule into the current namespace. That can be problematic.

math模块中的所有内容导入当前命名空间。那可能是有问题的

回答by randomusername

When you only use import maththe sqrtfunction comes in under a different name: math.sqrt.

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

回答by metersk

If you only import mathto call sqrtfunction you need to do this:

如果您只import math调用sqrt函数,则需要执行以下操作:

In [1]: import math

In [2]: x = 2

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

This is because from math import sqrtbrings you the sqrtfunction, but import mathonly brings you the module.

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

回答by Blake

If you need a square root, you can also just exponentiate a number by 0.5.

如果您需要平方根,您也可以将数字取指数 0.5。

144 ** 0.5

gives the result:

给出结果:

12.0