Programming with Python › Python Setup and First Programs › Day 43
Day 43: Installing Python and Virtual Environments
After this lesson you will have a working Python you can run from the terminal, and you will be able to create, activate, and reproduce an isolated virtual environment for any project — the foundation every reproducible AI project stands on.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/programming-with-python/day-043-installing-python-and-virtual-environments
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
cd labs/sections/programming-with-python/day-043-installing-python-and-virtual-environments - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Explain why Python is the dominant language for AI work: readability, a huge library ecosystem, and its role as a glue language
- Describe how Python runs code through the interpreter, distinguish a script from the REPL, and know why the course uses python3 rather than python
- Install Python by at least one method (python.org, an OS package manager, or pyenv for multiple versions) and use which python to confirm which interpreter runs
- Explain what a virtual environment is and why isolating each project's packages prevents global pollution and version conflicts
- Create, activate, and deactivate a virtual environment with python -m venv, and install packages into it with pip
- Capture a project's dependencies in a requirements.txt file and recreate the same environment elsewhere, connecting isolation to reproducible AI work
Prerequisites
- Course 1 fluency: comfort with the terminal, PATH (Day 11), and package managers (Day 13)
- A computer running macOS, Linux, or Windows with permission to open a terminal and install software
Why this matters
-
Nothing else in this course runs until this works. Every lesson from here assumes a Python you control.
-
“It works on my machine” is usually an environment problem, and virtual environments are the fix rather than a formality.
-
Two projects will want different versions of the same library. Without isolation, installing one breaks the other.
-
Every AI setup guide opens with these commands. Learning them once removes a recurring source of confusion.
-
This is Week 7, and it is the point where you stop driving other people’s programs and start writing your own.
The idea in plain language
-
Python is a program that runs your files. You can have several installed at once, and only one answers when you type
python3. -
A virtual environment is a private folder of packages for one project.
-
Activating it rewires your shell so
pythonandpipmean that project’s copies rather than the system’s. -
requirements.txtwrites the environment down, so another machine can rebuild it exactly. -
Nothing here is magic. It is Day 11’s
PATH, applied to Python.
Historical background
-
Python shipped without any isolation. Every package went into one system-wide directory, shared by every project on the machine.
-
That worked until two projects needed different versions, at which point installing one silently broke the other — the problem that came to be called dependency hell.
-
virtualenvappeared in 2007 as a third-party fix, and was popular enough that the idea was absorbed into the language itself. -
venvbecame part of the standard library in Python 3.3, which is why you need install nothing to use it today. -
The system Python is still a trap. On macOS and Linux the operating system uses its own Python for its own tools, and installing into it can break them.
-
Every later tool — Poetry, pipenv, uv, conda — solves the same problem, and most of them build on the same mechanism.
What it is — and what it is not
A virtual environment is:
- A directory holding its own
python,pipand installed packages. - Activated by a shell command that changes
PATHfor that shell only. - Disposable. Delete the folder and it is gone, with nothing else affected.
It is not:
-
Not a container. It isolates Python packages and nothing else — not the OS, not system libraries, not the CUDA driver.
-
Not a copy of Python. It links back to the interpreter that created it, which is why deleting that interpreter breaks the environment.
-
Not automatic. Creating one does not turn it on, and forgetting to activate is the single most common mistake here.
-
Not something to commit. The folder is large and machine-specific; the pinned file is what travels.
Why it was created and what problems it solves
-
Conflicting versions. Project A needs a library at 1.4 and project B at 2.0, and both can now have what they need.
-
Protecting the system Python. The operating system depends on its own Python, and installing into it can break tools you did not know existed.
-
Reproducibility. A pinned list rebuilds the same environment on another machine, which is what makes a result checkable.
-
Clean removal. Deleting a folder undoes an installation completely, with no residue anywhere else.
-
No administrator rights. Everything happens in a directory you own, so nothing needs
sudo.
How it works
Two ways to run code
-
python3with no filename lands you in the REPL — a>>>prompt where you type one expression, it evaluates, prints, and waits.exit()leaves. -
python3 hello.pyreads the whole file and runs it top to bottom. -
Both paths go through the same interpreter. A script hands it a file; the REPL hands it one line. Nothing else differs.
-
The REPL is your scratchpad; scripts are how programs are stored and shared.
Finding which Python you are running
-
You may have several installed — one from the operating system, one from python.org, one from a version manager — and only one answers to
python3. -
which python3prints the full path of the one that will run. -
python3 --versionprints its version. -
This is Day 11’s
PATH, deciding which program a bare name resolves to. -
“Which Python am I actually using?” is nearly always the first question when something behaves strangely.
Creating and using an environment
| Task | Command | What it does |
|---|---|---|
| Create | python3 -m venv .venv | Builds a folder with a private packages area |
| Activate | source .venv/bin/activate | Rewires this shell so python/pip mean the venv’s |
| Confirm | which python | Should print a path ending .venv/bin/python |
| Install | pip install <name> | Into the venv only, never globally |
| Pin | pip freeze > requirements.txt | Every package and its exact version |
| Rebuild | pip install -r requirements.txt | Exactly those versions, elsewhere |
| Turn off | deactivate | Restores the shell to the global Python |
-
-m venvmeans “run the standard-library module named venv”. -
The leading dot in
.venvis only a convention that keeps it tidy and easy to ignore. Any name works. -
Creating does not activate. They are two separate steps, and conflating them is the commonest mistake.
-
Your prompt usually shows
(.venv)once it is on, so you can see the state.
pip, PyPI, and requirements.txt
-
pipis Python’s package installer, downloading by default from the Python Package Index — the same idea as Day 13’s package managers, specialised for Python. -
pip install pandasfetches it and drops it into the active environment. -
pip freezelists everything installed with its exact version, likerequests==2.32.3. -
Redirect that to
requirements.txtand you have a precise recipe. -
Anyone — including future you — can rebuild it in a fresh venv with
pip install -r requirements.txt. -
This one file is how a project’s environment travels unchanged.
An everyday analogy
A shared workshop with personal toolboxes.
| The workshop | Python |
|---|---|
| The building and its power supply | The interpreter |
| The communal tool rack | The system packages |
| Your own locked toolbox | A virtual environment |
| Taking your toolbox to the bench | Activating |
| A written inventory of its contents | requirements.txt |
| Rebuilding an identical box from the list | pip install -r |
| Putting your box away | deactivate |
-
Everyone shares the building. Nobody shares toolboxes.
-
Borrowing from the communal rack works until two people need different versions of the same tool.
-
The inventory is the part that travels. You do not post the toolbox.
Examples in practice
-
pip installsucceeded andimportfails: you installed into one environment and are running another.which pythonandwhich pipsettle it. -
A
ModuleNotFoundErrorright after a successful install: the environment was never activated. -
Permission deniedfrompip: you are installing into the system Python. That is the signal to create an environment, not to reach forsudo. -
A project that worked last year and not today: unpinned dependencies moved underneath it.
-
A
.venvaccidentally committed: gigabytes of machine-specific files in a repository, and every clone pays for it.
Implications: security, privacy, performance, scalability, and cost
-
Security:
pip installruns code from strangers. Packages can execute at install time, and the name you type is the whole of the trust decision. -
Typosquatting is real here. Copy package names from documentation rather than typing them, exactly as on Day 13.
-
Never
sudo pip. It writes where the operating system’s own package manager believes it owns files, and the conflict surfaces weeks later. -
Performance: environments cost disk, not speed. A venv with PyTorch can be several gigabytes, and each project has its own.
-
Reproducibility: an unpinned dependency is a future breakage you have already scheduled and not yet noticed.
-
Cost: rebuilding an environment is cheap; reconstructing a lost one is not. Commit the pinned file, never the folder.
Alternatives: free, open source, and commercial
| Tool | Type | Where it fits |
|---|---|---|
venv | Free, standard library | The default. Nothing to install. |
uv | Free, open source | Same job, dramatically faster; increasingly the default |
| Poetry | Free, open source | Dependency resolution and packaging together |
| conda / mamba | Free, open source | Scientific stacks, including non-Python pieces like CUDA |
| pyenv | Free, open source | Managing several Python versions, not packages |
| Docker | Free, open source | When the whole environment must travel, not just packages |
-
uvis worth trying today. It creates environments and resolves dependencies fast enough to change how you work, and it understands the samerequirements.txt. -
conda earns its place in AI work because it manages CUDA libraries and other non-Python components that
pipcannot see.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Interpreter | The program that runs your Python code |
| Virtual environment | A private package directory for one project |
| Activate | Prepend the environment’s bin to PATH, for this shell |
| pip | The installer |
| PyPI | The public index it downloads from |
requirements.txt | The pinned list of what was installed |
| pyenv | Manages Python versions, not packages |
When to use it — and when not to
-
Create an environment for every project, from the first file. Retrofitting one is more work than starting with one.
-
Activate before installing anything. Check
which pythonif unsure. -
Pin before sharing, and commit
requirements.txtalongside the code. -
Add
.venv/to.gitignorebefore the first commit — Day 30’s rule. -
Do not install into the system Python, ever.
-
Do not commit the environment folder. It is large, machine-specific, and rebuildable from one file.
-
Do not reach for conda or Docker first. A venv solves most problems, and the heavier tools are for the ones it does not.
The AI connection
-
Every AI project starts with this command.
python3 -m venv .venvis the first line of almost every setup guide you will ever follow. -
AI dependencies conflict harder than most. Two projects wanting different PyTorch or CUDA builds cannot share one environment, and the failure is a cryptic import error rather than a clear refusal.
-
requirements.txtis half of reproducibility. A result you cannot rebuild is a result you cannot defend, and the environment is as much a part of the experiment as the code. -
Model libraries are large. A single environment with PyTorch is often several gigabytes, which is why they belong in
.gitignoreand not in a repository. -
The remote machine has its own environment. Your laptop’s venv does not travel; the pinned file does.
Knowledge check
quiz:
question: "A package installs successfully with pip, but importing it in the very next command raises ModuleNotFoundError. What is the most likely cause?"
options:
- "pip and python resolve to different installations, so the package went somewhere the interpreter is not looking"
- "The package requires a newer Python version than the one installed"
- "The install completed but the package index served a corrupted archive"
- "The package must be added to requirements.txt before it can be imported"
answer_index: 0
explanation: "pip and python are two separate programs found on PATH. If an environment is not activated — or is only half activated — pip may install into one location while python looks in another. Running which pip and which python side by side shows the mismatch immediately."
Hands-on exercise
Create an environment, prove the isolation, then rebuild it from a pinned file. Worked through fully in the Day 43 lab directory.
| What you are doing | Command |
|---|---|
| Find your interpreter | which python3 and python3 --version |
| Create an environment | python3 -m venv .venv |
| See that it is not on yet | which python |
| Activate it | source .venv/bin/activate |
| Confirm it worked | which python — now inside .venv |
| Install something | pip install requests |
| Pin it | pip freeze > requirements.txt |
| Leave, and rebuild elsewhere | deactivate, then a fresh venv and pip install -r |
Expected output
/usr/bin/python3
Python 3.12.4
/Users/you/project/.venv/bin/python
Successfully installed requests-2.32.3
requests==2.32.3
-
The path changed after activating. That is the entire mechanism —
PATH, from Day 11. -
pip freezepinned an exact version, not a range. That is what makes the rebuild identical.
Validate your work
- You can name which interpreter runs before and after activating
- You installed a package and confirmed it is not available once deactivated
- You produced a
requirements.txtwith pinned versions - You rebuilt the environment from that file in a different directory
-
.venv/is in your.gitignore -
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
source: no such file. The environment was not created, or you are in the wrong directory. Check that.venv/bin/activateexists. -
which pythonstill shows the system one. Activation did not take. It affects only the shell you ran it in — a new tab is not activated. -
pipinstalls butpythoncannot import. They resolve differently. Comparewhich pipwithwhich python. -
Windows uses a different activate path.
.venv\Scripts\activate.
Common mistakes
-
Creating and forgetting to activate.
-
Reaching for
sudowhenpipreports a permission error. That error is telling you to use an environment. -
Committing
.venv/. -
Pinning nothing, then wondering why the project stopped working.
Practice assignment
-
Create three environments for three throwaway projects and install a different version of the same package in each. Prove they do not interfere.
-
Break one deliberately by deleting the interpreter it was built from, and observe what happens.
-
Write a setup script that creates the environment, activates it, and installs from
requirements.txtin one command. -
Compare
venvwithuvon the same requirements file, and time both.
Extension challenge
-
Read what
activateactually does. Open the script; it is short, and it is entirelyPATHmanipulation plus a saved copy to restore ondeactivate. -
Inspect a venv’s layout. Find the interpreter, the packages directory and the file recording which Python created it.
-
Pin transitively and compare.
pip freezerecords everything installed, including dependencies of dependencies. Count how many you did not ask for. -
Reproduce dependency hell on purpose: two packages with incompatible requirements in one environment, and read what the resolver says.
Quiz
Q1. What is the Python "interpreter"?
- A website that translates Python into other programming languages
- The program (run as python3) that reads your code and executes it
- A file that lists which packages a project needs
- The folder where installed packages are stored
Show answer
Answer: B. The program (run as python3) that reads your code and executes it
Python is both a language and the program that runs code written in it. That program is the interpreter, usually invoked as python3, and it can run a whole script file or accept lines interactively in the REPL.
Q2. What is the difference between running a script and using the REPL?
- The REPL runs faster because it skips the interpreter
- A script needs a virtual environment but the REPL does not
- A script runs a file; the REPL evaluates one line at a time
- Scripts use python3 while the REPL uses a completely different program
Show answer
Answer: C. A script runs a file; the REPL evaluates one line at a time
Both feed the same interpreter. Handing it a file (python3 hello.py) runs the whole file top to bottom; starting python3 with no file gives the REPL — read, evaluate, print, loop — where you type one line at a time.
Q3. Why does this course prefer the command python3 over python?
- python3 runs three times faster than python
- python is only available on Windows
- python cannot create virtual environments
- python often meant Python 2; python3 names Python 3
Show answer
Answer: D. python often meant Python 2; python3 names Python 3
During the long overlap between Python 2 and Python 3, many machines shipped both, with python meaning the old Python 2. python3 removes the ambiguity and works portably across systems.
Q4. What problem does a virtual environment primarily solve?
- Projects keep their own package versions without conflict
- It makes Python code run faster at runtime
- It encrypts your source code for security
- It replaces the need to install Python at all
Show answer
Answer: A. Projects keep their own package versions without conflict
Without isolation, all projects share one global pile of packages, so one project needing a different version of a library breaks another. A venv gives each project a private package folder, ending those collisions.
Q5. After running source .venv/bin/activate, how can you confirm the environment is active?
- Restart the computer and check again
- Run which python and see a .venv path
- Check that the file requirements.txt exists
- Run python3 --version and confirm it prints 3.x
Show answer
Answer: B. Run which python and see a .venv path
Activation rewires the current shell so python and pip point inside the venv. which python then prints a path inside .venv, and most shells also show a (.venv) marker in the prompt. sys.prefix pointing inside .venv is the definitive proof.
Q6. What is the relationship between pip and PyPI?
- They are two names for the same program
- pip is the online repository and PyPI is the installer
- pip is the installer; PyPI is the repository it downloads from
- PyPI is a virtual environment manager and pip creates environments
Show answer
Answer: C. pip is the installer; PyPI is the repository it downloads from
pip is the tool that installs packages, and by default it fetches them from PyPI, the public online index of open-source Python libraries — the Python-specific version of the package-manager idea from Day 13.
Q7. What does a requirements.txt file give you?
- A backup copy of your source code
- Automatic activation of the virtual environment
- A faster interpreter for large projects
- A text recipe of exact packages and versions
Show answer
Answer: D. A text recipe of exact packages and versions
pip freeze writes every installed package and its exact version to requirements.txt. Running pip install -r requirements.txt in a fresh venv rebuilds the identical set of packages, which is what makes an environment reproducible across machines and time.
Q8. You need Python 3.11 for one project and Python 3.13 for another on the same machine. Which tool is designed for that?
- pyenv, which switches between Python versions
- pip, by installing both versions
- venv, by creating two environments
- requirements.txt, by listing both versions
Show answer
Answer: A. pyenv, which switches between Python versions
A venv isolates packages but shares one base interpreter. Switching between different Python versions is a separate job handled by a version manager like pyenv, which installs and selects among multiple Python versions and pairs with venv rather than replacing it.
Glossary
- interpreter
- The program (run as python3) that reads Python code and executes it, either from a whole script file or one line at a time in the REPL.
- REPL
- The read-eval-print loop: Python's interactive prompt (>>>), where you type one line, it evaluates and prints the result, then waits for the next line.
- script
- A file of Python code, run all at once with python3 filename.py, as opposed to typing lines interactively in the REPL.
- virtual environment
- A lightweight, isolated folder that gives one project its own private set of installed packages, kept separate from the global Python and from other projects.
- venv
- Python's built-in module for creating virtual environments, used as python3 -m venv .venv; also a common name for the environment folder it creates.
- activate
- To turn on a virtual environment (source .venv/bin/activate), which rewires the current shell so python and pip point inside that environment; deactivate turns it off.
- pip
- Python's package installer: the tool that downloads and installs libraries into whichever environment is active, by default from PyPI.
- PyPI
- The Python Package Index, the public online repository of open-source Python libraries that pip downloads from by default.
- package
- A reusable library of Python code, published on PyPI and installed with pip, that adds functionality beyond the standard library.
- dependency
- A package that a project needs in order to run; a project's dependencies (and their exact versions) are what a virtual environment isolates and requirements.txt records.
- requirements.txt
- A plain-text file listing a project's packages and their exact versions, used with pip install -r requirements.txt to recreate the same environment elsewhere.
- pyenv
- A tool that installs and switches between multiple versions of Python on one machine; it manages Python versions and pairs with venv, which manages packages.
- standard library
- The large set of modules that ships with Python itself, available without installing anything from PyPI.
Sources and further reading
- venv — Creation of virtual environments — Python Software Foundation (accessed 2026-07-12)
- Installing Python Modules — Python Software Foundation (accessed 2026-07-12)
- The Python Tutorial — Python Software Foundation (accessed 2026-07-12)
- Python Virtual Environments: A Primer — Real Python (accessed 2026-07-12)
- Python (programming language) — Wikipedia (accessed 2026-07-12)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.