Error guide · NameError
NameError: name 'np' is not defined
You used np without importing NumPy under that name.
Example
print(np.array([1, 2, 3]))
What Python says
NameError: name 'np' is not defined
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
np is only a nickname, and it exists after the line import numpy as np. Without that line Python has never heard of np. A line such as import numpy as n gives the same error when the code still says np.
How to fix it
import numpy as np print(np.array([1, 2, 3]))
Output: [1 2 3]
Tips
- Start every NumPy program with
import numpy as np. - Use the same nickname everywhere in the program.
- If the import line is there and the error remains, check the spelling of
np.