0

I don't understand why I can't use numpy. after I give it an alias.

I got an error for this.

import numpy as np

ar = numpy.array([1,2,3,4,5])

print(ar)

I can only type

import numpy as np

ar = np.array([1,2,3,4,5])

print(ar)
Zero
  • 1,807
  • 1
  • 6
  • 17
  • 3
    The whole point of using `as` is so you can use the alias you've given. If you don't want to use `ar = np.array(...)` just do `import numpy` and then you can use `ar = numpy.array(...)` instead. – JRiggles Jul 04 '23 at 17:41
  • Does this answer your question? [Can you define aliases for imported modules in Python?](https://stackoverflow.com/questions/706595/can-you-define-aliases-for-imported-modules-in-python) – Zero Jul 04 '23 at 17:42
  • @Zero I don't think that's really the question. If I understand correctly, OP just wants to be able to use the `numpy` namespace as-is. I suspect they aren't 100% familiar with how imports work yet. – JRiggles Jul 04 '23 at 17:43
  • @JRiggles, I put the link here so OP can get a better understanding of aliasing in python. – Zero Jul 04 '23 at 17:44

1 Answers1

3

That is just how the import ... as statement behaves. You choose one name for the module you are importing. If you don't have an as clause, the module’s own name is used.

If you want to call numpy numpy, do

import numpy

if you want to call numpy np, do

import numpy as np

and if, for some bizarre reason, you want to be able to use either, do

import numpy

np = numpy
LeopardShark
  • 3,820
  • 2
  • 19
  • 33
  • 1
    Another option if someone wants to use both, for some reason, is to just list both imports, i.e. have both `import numpy` and `import numpy as np`. – jared Jul 04 '23 at 18:06