NameError:名称“sqrt”未在 Python 中定义
NameError: name ‘sqrt’ is not defined in Python
Python“NameError: name ‘sqrt’ is not defined”发生在我们使用该
sqrt
函数而不先导入它时。解决import sqrt
from math
( from math import sqrt
)的错误。如果使用,请从
( )numpy
导入。sqrt
numpy
from numpy import sqrt
下面是错误如何发生的示例。
# ⛔️ NameError: name 'sqrt' is not defined print(sqrt(25))
要解决该错误,请从数学模块中导入
sqrt函数
。
# ✅ import sqrt function first from math import sqrt print(sqrt(25)) # 👉️ 5.0
如果您使用,则改为从模块numpy
导入函数sqrt
numpy
from numpy import sqrt print(sqrt([1, 4, 9])) # 👉️ [1. 2. 3.]
Alternatively, you can import the entire module.
import numpy as np print(np.sqrt([1, 4, 9])) # 👉️ [1. 2. 3.]
We imported the numpy
module and aliased it to np
, so we can access the
sqrt
function as np.sqrt()
.
You can use the same approach when using the build-in math
module.
import math print(math.sqrt(25)) # 👉️ 5.0
Even though the math
module is in the Python standard library, we still have
to import it before using it.
Make sure you haven’t misspelled anything in the import statement because module
and function names are case-sensitive.
Also, make sure you haven’t imported the module in a nested scope, e.g. a
function. Import the module at the top level to be able to use it throughout
your code.
In general it is better to import only the functions you intend to use in your
code.
# ✅ import sqrt function first from math import sqrt print(sqrt(25)) # 👉️ 5.0
import math
, it is much harder to see which functions from the math
module are being used in the file.Conversely, when we import specific functions, it is much easier to see which
functions from the math
module are being used.
The math
module provides access to many mathematical functions that are
defined by the C standard.
You can view all of the functions and constants the math
module provides by
visiting the official docs.
Conclusion #
Python“NameError: name ‘sqrt’ is not defined”发生在我们使用该
sqrt
函数而不先导入它时。解决import sqrt
from math
( from math import sqrt
)的错误。如果使用,请从
( )numpy
导入。sqrt
numpy
from numpy import sqrt