Error guide · NameError
NameError: name 'math' is not defined
You used the math module without importing it first.
Example
print(math.sqrt(16))
What Python says
NameError: name 'math' is not defined. Did you forget to import 'math'?
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
Modules are not available until you import them. Python sees math in your code, finds no variable with that name, and stops. The import line must come before the first use, normally at the top of the program.
How to fix it
import math print(math.sqrt(16))
Output: 4.0
Tips
- Put
import mathat the top of the program. - The same message appears for
random,datetimeand other modules. - If you wrote
from math import sqrt, callsqrt(16)withoutmath.in front.