Chapter 2, Environment
Installing and importing NumPy
Two lines get NumPy ready, and most beginner problems come from the installation ending up in a different Python than the one you are using.
Code for this chapter: ambiente/cap02_instalacao.py
Install
NumPy installs like any Python package, inside a virtual environment, as the Python course showed. Choose the tool you use:
uv init meu-projeto
cd meu-projeto
uv add numpy
The uv add creates the environment, installs the package and registers it in pyproject.toml. To run a file in the project environment, use uv run arquivo.py.
NumPy distributes pre-compiled versions (wheels) for the most common systems and Python versions. Therefore, the installation takes seconds and does not require a compiler.
Import, and the convention `np`
import sys
from pathlib import Path
import numpy as np
print("versão 2 ou superior:", int(np.__version__.split(".")[0]) >= 2)
print("onde está o NumPy:", Path(np.__file__).parent.name)
print("este Python existe no disco:", Path(sys.executable).exists())
versão 2 ou superior: True
onde está o NumPy: numpy
este Python existe no disco: True
The alias np is not a language rule, but it is such a strong convention that all documentation, every tutorial, and every answer on the internet assumes it. Using another alias just makes you translate what you read.
To see how your NumPy was built (which linear algebra libraries it uses, for example), there is the show_config:
np.show_config()
When the import fails
The most common error is installing with the pip in a terminal and receiving No module named 'numpy' in the editor. Almost always this means that there are two different Pythons: the one in the terminal received the package, and the one in the editor (or the notebook) did not. To find out which Python is running and if it sees NumPy:
python -c "import sys; print(sys.executable)"
python -m pip show numpy
python -c "import numpy; print(numpy.__version__, numpy.__file__)"
| Symptom | Probable cause | What to do |
|---|---|---|
No module named 'numpy' in the editor | The editor uses another interpreter | Select the interpreter from the .venv of the project |
No module named 'numpy' only in the notebook | The kernel is from another environment | Install ipykernel in the environment and choose that kernel |
| Unexpected version | Two environments with different versions | Compare sys.executable in both places |
| Installation error due to lack of compiler | Python version without wheel available | Use a supported version of Python for the package |
The rule that saves me time
Always use
python -m pipinstead ofpippure. This way, thepipis necessarily the one from the interpreter you called, and the package lands in the right place.
Exercise 1
A diagnosis of the environment
Write diagnostico() that returns a dictionary with the version of NumPy, the version of Python (as a tuple of two numbers), and whether the Python executable exists on disk.