close

[Solved] Error NameError: name ‘np’ is not defined

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Error NameError: name ‘np’ is not defined in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Error NameError: name ‘np’ is not defined Error Occurs?

Today I get the following error Error NameError: name ‘np’ is not defined in python.

How To Solve Error NameError: name ‘np’ is not defined Error ?

  1. How To Solve Error NameError: name 'np' is not defined Error ?

    To Solve Error NameError: name 'np' is not defined Error This imports the package numpy, and everything inside of that package. However, numpy does not contain a module called np. The typical practice for numpy is to instead do

  2. Error NameError: name 'np' is not defined

    To Solve Error NameError: name 'np' is not defined Error This imports the package numpy, and everything inside of that package. However, numpy does not contain a module called np. The typical practice for numpy is to instead do

Solution 1

“change from numpy import * to import numpy as np“:

import numpy as np
...

Or don’t write np:

from numpy import *
x = random.randint(low=10, high=30, size=6)
...

Because, from numpy import *, Import every function in numpy, so np is not a function of numpy, so have to Import numpy like import numpy as np, Or, Remove np part of np.random.randint(low=10, high=30, size=6), and make it like this: random.randint(low=10, high=30, size=6), it’s all since random is a function of numpy, basically that’s all, to explain

Solution 2

You haven’t defined np.

The first thing you’re currently doing is

from numpy import *

This imports the package numpy, and everything inside of that package. However, numpy does not contain a module called np. The typical practice for numpy is to instead do

import numpy as np

This imports just the package numpy, and renames it to np so that you can dereference it by using the dot operator on np. This allows you to call np.random(), since random is a member of numpy, which is aliased to np.

With what you’re currently doing, you could do either numpy.random() or just random (since it was part of the * that you imported from numpy).

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read