NameError:名称“sqrt”未在 Python 中定义

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导入sqrtnumpyfrom numpy import sqrt

nameerror 名称 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导入函数sqrtnumpy

主程序
from numpy import sqrt print(sqrt([1, 4, 9])) # 👉️ [1. 2. 3.]

Alternatively, you can import the entire module.

main.py
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.

main.py
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.

main.py
# ✅ import sqrt function first from math import sqrt print(sqrt(25)) # 👉️ 5.0
For example, when we use an import such as 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导入sqrtnumpyfrom numpy import sqrt