Python for ML
Setting Up Your Python Environment
A practical, step-by-step setup: installing Python, using pip, isolating projects with virtual environments and getting NumPy, Pandas, Matplotlib and scikit-learn installed.
beginner · 12 min read
Lesson content
Every lesson from here on assumes you can open a terminal, run Python and install a library without it turning into a debugging session of its own.
This is that one-time setup. Done carefully it saves hours of confusion later, and almost all of that confusion comes from one thing: having more than one Python on your machine and not knowing which one you are talking to.
The setup checklist
Install Python
Get Python itself onto your computer, if it is not already there.
Verify it
Confirm from a terminal which version is actually running.
Isolate your project
Create a virtual environment so this project's libraries do not collide with any other project's.
Pick an editor
Set up VS Code (or similar) so you can write and run code comfortably.
Set up notebooks
Install Jupyter, or use Google Colab, for the notebook-style workflow most ML learning uses.
Install the libraries
Add NumPy, Pandas, Matplotlib and scikit-learn, the four libraries nearly every lesson from here on relies on.
Most machines already have some version of Python installed. macOS and most Linux distributions ship with one.
Whether that is true for you, and whether it is recent enough, is worth checking before you install anything.
python3 --versionpython --versionpython3 --versionOn macOS and Linux, python3 is almost always the right command. It explicitly asks for Python 3, avoiding any ambiguity with an old Python 2 that might also be present.
python --versionOn Windows, plain python usually points at Python 3 already. Try whichever command exists on your system. If both work, prefer python3 when it is available.
If neither command prints something like Python 3.11.4, or the version shown is older than about 3.9, install a fresh copy from python.org.
On Windows, check the box labeled "Add python.exe to PATH" during installation. Skipping it is the single most common reason python is not recognized afterwards, and it is much easier to tick the box than to fix PATH by hand later.
On macOS or Linux, the installer or your system's package manager, such as apt on Ubuntu, handles this automatically.
Definition
pip
Python's built-in tool for installing and managing libraries other people have written.
Formal definition
The standard package manager for Python, used to install, upgrade and remove packages from the Python Package Index (PyPI) and other sources.
pip is installed automatically alongside Python, so there is usually nothing extra to set up. It is worth confirming it is present and reasonably up to date before relying on it.
pip3 --versionpython3 -m pip install --upgrade pippip3 --versionThis prints pip's version and, usefully, which Python installation it is attached to. Worth checking whenever you have more than one Python on the machine.
python3 -m pip install --upgrade pipRunning pip through python3 -m pip (rather than calling pip3 directly) guarantees the upgrade applies to the exact Python you just checked in the line above, not a different one that happens to also be on your system.
Why use a virtual environment?
Because projects disagree about versions, and there is only one global Python to disagree in.
One project might need an older scikit-learn while another needs the newest release. Install everything globally and every project is forced onto the same versions, so upgrading a library for one can silently break another.
A virtual environment gives each project its own private set of installed libraries. Changes in one project then cannot ripple into any other, which is worth the thirty seconds it takes to create.
Definition
Virtual environment
A self-contained, isolated copy of Python and its installed libraries, kept separate for one project.
Formal definition
An isolated Python runtime with its own site-packages directory, created so that a project's dependencies are independent of the system Python and of other projects' environments.
That picture is worth holding on to, because it explains every confusing thing about environments in one go.
Activating does not install anything, move anything or change Python itself. It edits the order of the folders Python looks through when you write import.
So the environment is not magic. It is a folder, plus a rule about which folder gets looked at first.
python3 -m venv ml-envsource ml-env/bin/activatepython3 -m venv ml-envThis creates a folder named ml-env holding a private copy of Python and an empty library list. That folder is the environment. On Windows the same command is python -m venv ml-env.
source ml-env/bin/activateactivate switches your current terminal session to use that private Python and its libraries instead of the system-wide one. On Windows, the equivalent command is ml-env\Scripts\activate. You will need to run this activation command again each time you open a new terminal for this project.
Once activated, your terminal prompt usually changes to show the environment's name, like (ml-env). That prefix is your confirmation.
Everything installed with pip from this point goes into ml-env alone, never the system Python.
pip install numpy pandas matplotlib scikit-learnpip install numpy pandas matplotlib scikit-learnThis installs the four libraries used throughout this site: numpy for numerical arrays, pandas for tabular data, matplotlib for plotting and scikit-learn for the machine learning algorithms themselves.
With Python and the libraries in place, you need somewhere to actually write and run code.
VS Code is a solid, free choice. Install it, then install its official Python extension from the Extensions panel.
Then run "Python: Select Interpreter" from the command palette and point it at your ml-env virtual environment specifically. This step is easy to skip and it matters: without it, VS Code may run your code with a different Python that has none of your libraries, and every import turns red for no apparent reason.
Definition
Jupyter notebook
A document that mixes runnable code, its output and written explanation in one file, run one small piece (a "cell") at a time.
Formal definition
An interactive, cell-based document format that interleaves executable code, rendered output (including plots) and formatted text, commonly used for exploratory data analysis and machine learning.
Why use notebooks instead of a normal script?
Machine learning work is exploratory. You load some data, look at it, tweak something and look again.
A notebook lets you run one small piece of code at a time and immediately see its output (including a plotted chart) right below it, without rerunning an entire script from scratch after every change. That tight loop of "run a little, look, adjust" is why nearly every lesson on this site that shows code output assumes a notebook-style workflow.
pip install jupyterjupyter notebookpip install jupyterInstalls Jupyter into your active virtual environment, alongside the libraries installed earlier.
jupyter notebookLaunches the notebook interface in your browser, starting from your current folder. From there, create a new notebook and start writing code in cells.
If installing anything locally feels like too much friction to start, Google Colab is a free, browser-based alternative: it runs Jupyter-style notebooks entirely in Google's cloud, with NumPy, pandas, Matplotlib and scikit-learn already installed. It needs nothing more than a Google account and a browser tab.
| Local (venv + Jupyter) | Google Colab | |
|---|---|---|
| Setup effort | Install Python, create a venv, install libraries | None, open a browser tab |
| Works offline | Yes | No, requires an internet connection |
| Your own files | Directly on your computer | Uploaded, or connected via Google Drive |
| Good for | Ongoing projects, full control over versions | Getting started fast, or a machine with no setup rights |
Setup effort
- Local (venv + Jupyter)
- Install Python, create a venv, install libraries
- Google Colab
- None, open a browser tab
Works offline
- Local (venv + Jupyter)
- Yes
- Google Colab
- No, requires an internet connection
Your own files
- Local (venv + Jupyter)
- Directly on your computer
- Google Colab
- Uploaded, or connected via Google Drive
Good for
- Local (venv + Jupyter)
- Ongoing projects, full control over versions
- Google Colab
- Getting started fast, or a machine with no setup rights
import numpyimport pandasimport matplotlibimport sklearnprint("numpy:", numpy.__version__)print("pandas:", pandas.__version__)print("matplotlib:", matplotlib.__version__)print("scikit-learn:", sklearn.__version__)import numpy
import pandas
import matplotlib
import sklearnIf every import here runs without an error, all four libraries installed correctly into whichever Python is currently running this file.
print("numpy:", numpy.__version__)
print("pandas:", pandas.__version__)
print("matplotlib:", matplotlib.__version__)
print("scikit-learn:", sklearn.__version__)Printing each version is a quick sanity check, and useful later if an example ever behaves differently across library versions.
ModuleNotFoundError right after a successful install
This is the error that eats an afternoon, and the figure above already explains it.
pip install pandas put pandas into whichever environment that terminal was pointed at. Your notebook then ran import pandas from a different Python, which searched its own folders and found nothing.
The install succeeded. The import failed. Both are telling the truth.
To find out who is talking to whom, run import sys; print(sys.executable) in the notebook and compare it with which python in the terminal. If the two paths differ, that is your answer, and pointing your editor at the right interpreter fixes it.
Typing python on a system where only python3 is set up (or the reverse) and concluding Python is not installed at all.
Try both python and python3, and both pip and pip3, before assuming nothing is installed. Many systems recognize only one of each pair, and which one varies by operating system.
Running pip install successfully, but then getting ModuleNotFoundError when importing the same library.
The install and the import happened in two different Pythons. Check that your environment is activated in the terminal where you ran pip install, and that your notebook or editor is pointed at the same one.
Key takeaway
- Confirm Python is installed and check its version before assuming anything is missing. Try both
pythonandpython3. - A virtual environment keeps one project's libraries isolated from every other project's, avoiding version conflicts.
- VS Code with its Python extension, Jupyter, and Google Colab are all reasonable ways to write and run ML code. Colab needs no local setup at all.
ModuleNotFoundErrorafter a successfulpip installalmost always means the install and the run happened in different Python environments.
Finished this lesson?
Guest progress is saved on this device.