NameError:名称“math”未在 Python 中定义
NameError: name ‘math’ is not defined in Python
Python“NameError: name ‘math’ is not defined”发生在我们使用
math
模块而不先导入它时。要解决错误,请math
在使用之前导入模块 – import math
。
下面是错误如何发生的示例。
# ⛔️ NameError: name 'math' is not defined print(math.ceil(1.2)) print(math.floor(1.7))
为了解决错误,我们必须导入
数学模块。
import math print(math.ceil(1.2)) # 👉️ 2 print(math.floor(1.7)) # 👉️ 1
即使该math
模块在 Python 标准库中,我们仍然需要在使用前导入它。
m
when importing math
because module names are case-sensitive.Alternatively, you can make your code a little more concise by only importing
the functions that you use in your code.
from math import ceil, floor print(ceil(1.2)) # 👉️ 2 print(floor(1.7)) # 👉️ 1
The example shows how to import the ceil()
and floor()
functions from the
math
module.
Instead of accessing the functions on the module, e.g. math.floor()
, we now
access them directly.
This should be your preferred approach because it makes your code easier to
read.
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.
The math
module also provides some commonly used constants, e.g. pi
.
from math import pi print(pi) # 👉️ 3.141592653589793
You can view all of the functions and constants the math
module provides by
visiting the official docs.
Conclusion #
The Python “NameError: name ‘math’ is not defined” occurs when we use the
math
module without importing it first. To solve the error, import the math
module before using it – import math
.