NameError: name 'math' is not defined,两种情况

NameError: name 'math' is not defined

python抛出这种NameError,并提示name 'math' is not defined,那么一般的原因有如下两种:

  1. 一般情况下是因为没有导入math模块而直接使用math模块所导致的;
  2. 也可能是因为math并不是作为模块使用,而是作为变量名,却没有声明而导致的;

解决的方法

  1. 如果是第一种情况,则用import导入math模块即可;
  2. 如果是第二种情况,则声明变量并赋值即可;

两种情况的实例代码

>>> math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> math = 1
>>> math
1
>>> import math
>>> math.e
2.718281828459045

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.