aria-label="Breadcrumb"> Home/ Modules/ Python Foundations/ Lesson 01
Lesson 1 of 12 — Python Foundations
Lesson 01 core ~8 min

Setting Up a Secure Python Environment

Before you write a single line of Python, the environment you write it in determines how much damage a mistake can do. This lesson covers everything you need to set up an isolated, auditable Python environment — and why skipping this step creates vulnerabilities that no amount of careful coding can fix later.

Why Your Environment Is a Security Boundary

When Python installs packages globally, every project on your machine shares the same pool of dependencies. A vulnerability in a library used by one project is a vulnerability in all of them. A malicious package installed for one purpose has access to everything. The environment is not just an organisational tool — it is a containment boundary.

Security Risk

Installing packages globally with pip install package-name without a virtual environment means every project shares those dependencies. One compromised or vulnerable package affects your entire system Python installation.

The solution is virtual environments — isolated Python installations where each project gets its own packages, its own versions, and its own blast radius if something goes wrong.

Global vs. Isolated: What Changes

# environment_isolation.py

Each project has its own .venv directory containing a complete, isolated Python installation. Packages installed in one virtual environment are invisible to all others. When you delete the project, you delete the environment with it — no cleanup required, no global state left behind.

Check Your Python Version Before You Start

Before creating a virtual environment, confirm you are running Python 3.14 or later. Earlier versions can cause problems during venv setup on Windows. Open your terminal and run:

Windows — Command Prompt or PowerShell
python --version
macOS / Linux
python3 --version
If you see Python 3.13 or earlier — update before continuing

Go to python.org/downloads and download the standalone installer for Python 3.14. When the installer opens, make sure "Add python.exe to PATH" is checked before clicking Install Now. On the final screen, click "Disable path length limit" if it appears — this removes a Windows restriction that can cause problems with deeply nested project folders.

After installation completes, close your terminal or VS Code completely and reopen it, then run python --version again to confirm it now shows 3.14. You need the full restart for the new PATH entry to take effect.

The troubleshooting callout in the VS Code instructions below covers what to do if you proceed without upgrading and hit errors — but upgrading first is the cleaner path.

Creating a Virtual Environment — Step by Step

Python ships with venv built in — you do not need to install anything extra. The steps below differ slightly depending on which tool you are using. You do not need administrator or admin privileges to create a virtual environment. This is intentional — a tool that requires admin rights to set up a project is a security risk in itself.

First: Create a project folder

Before you create a virtual environment, you need a folder for your project. Create a folder somewhere on your computer — for example C:\PythonCourses\secure-python on Windows or ~/Documents/secure-python on macOS/Linux. Everything in this lesson goes inside that folder. Do not put it on your Desktop or in a cloud-synced folder like OneDrive or Google Drive — syncing a virtual environment causes problems.

Common Mistake — .venv in the wrong place

If you run python -m venv .venv before navigating into your project folder, the .venv folder is created in whatever directory your terminal was already in — not inside your project. The result looks like C:\Users\yourname\.venv sitting alongside your secure-python folder instead of inside it. If this happens, delete that .venv folder, cd into your project folder first, then run the command again. Always confirm the terminal prompt shows your project path before running python -m venv .venv.

The steps differ depending on which tool you are working in. Select yours below to see the instructions for your setup.

Which tool are you using?

Open Command Prompt by pressing the Windows key, typing cmd, and pressing Enter. You do not need to run it as administrator.

Shortcut — open cmd directly inside your folder

In File Explorer, navigate into your secure-python folder, click the address bar so it becomes editable, type cmd, and press Enter. Command Prompt opens already inside that folder — no navigation needed.

If you need to navigate manually

Command Prompt opens in C:\Users\username by default. The fastest approach is a direct path: cd C:\YourFolderPath\secure-python. Replace the path with wherever you created your project folder. Once the prompt shows your project path, run the commands below.

Windows — Command Prompt
# Step 1: Navigate into your project folder # Replace the path with wherever you created your folder cd C:\PythonCourses\secure-python # Step 2: Create the virtual environment # This creates a .venv folder inside your project folder python -m venv .venv # Step 3: Activate it .venv\Scripts\activate # You will see (.venv) appear at the start of your prompt # That means it is working. Example: # (.venv) C:\PythonCourses\secure-python> # Step 4: Confirm Python is coming from the venv where python # First result should show: C:\PythonCourses\secure-python\.venv\Scripts\python.exe
If python is not recognized

Errors you might see:
'python' is not recognized as an internal or external command
Python was not found; run without arguments to install from the Microsoft Store

These mean Python is either not installed or not on your PATH. Try py -m venv .venv — Windows sometimes installs Python under the py launcher. If that works, use py everywhere this lesson says python. If neither works, rerun the Python installer and make sure "Add Python to PATH" is checked on the first screen.

▶ Python is not installed — click here for installation instructions

Step 1: Download Python
Go to python.org/downloads and download the latest stable version for your operating system. As of this writing that is Python 3.14. Do not download Python 2 — it is end of life and not covered on this site.

Windows installation — critical step
Run the installer. On the very first screen, before clicking anything else, check the box that says "Add Python to PATH". This is the step many beginners miss. Without it, Windows cannot find Python when you type python in the Command Prompt. After checking that box, click Install Now.

After installing — verify it worked
Close Command Prompt completely, open a new one, and run python --version. You should see something like Python 3.14.x. Once you see that, come back and run the venv commands above.

On macOS, open Terminal from Applications → Utilities. On Linux, open your terminal emulator. You do not need elevated privileges to create a virtual environment.

macOS / Linux — Terminal
# Step 1: Navigate into your project folder cd ~/Documents/secure-python # Step 2: Create the virtual environment # This creates a .venv folder inside your project folder python3 -m venv .venv # Step 3: Activate it source .venv/bin/activate # You will see (.venv) appear at the start of your prompt # That means it is working. Example: # (.venv) username@machine secure-python % # Step 4: Confirm Python is coming from the venv which python3 # Should show: /Users/username/Documents/secure-python/.venv/bin/python3
If python3 is not found

Errors you might see:
command not found: python3
python3: No such file or directory

These mean Python 3 is not installed or not on your PATH. Install it through your package manager:
Ubuntu/Debian: sudo apt install python3 python3-venv
Fedora: sudo dnf install python3
Arch: sudo pacman -S python

macOS: download the installer from python.org/downloads and run the .pkg file. Always use python3, never python, on macOS — the system ships with an older Python 2 under that name.

VS Code has built-in virtual environment support. The key difference from using a standalone terminal is that VS Code's built-in terminal opens already inside your project folder — so the .venv is created in the right place automatically as long as you open your project folder in VS Code first.

Steps

1. Open VS Code and choose File → Open Folder — select your secure-python project folder. VS Code will open it and may immediately show a prompt that says "Do you trust the authors of the files in this folder?" — since this is your own folder, click "Yes, I trust the authors". Leave the checkbox for the parent folder unchecked. This prompt appears the first time you open any folder and is not a warning that something is wrong; it just needs your confirmation before enabling all features.

2. Open the built-in terminal: Terminal → New Terminal (or use the keyboard shortcut — on Windows press Ctrl + `, on Mac press Cmd + `, where ` is the backtick key, found in the top-left corner of most keyboards directly above the Tab key, sharing the key with the tilde ~ character). The terminal opens already inside your project folder.
3. Run python -m venv .venv on Windows, or python3 -m venv .venv on Mac/Linux.
4. VS Code will show a popup: "We noticed a new virtual environment was created. Do you want to select it for the workspace?" — click Yes.
5. VS Code now uses your .venv automatically. You will see (.venv) in the bottom status bar and in any new terminal you open inside this project.

If the popup does not appear

Press Ctrl+Shift+P (Windows) or Cmd+Shift+P (Mac), type Python: Select Interpreter, and choose the entry that shows .venv in its path. You only need to do this once per project.

Windows — if you see a long error ending in KeyboardInterrupt after running the venv command

This is a known issue on Windows where pip's bootstrapper fails during venv creation when running in PowerShell — the error traces back through _setup_pip and ensurepip. It can affect any Python version. VS Code's built-in terminal uses PowerShell by default on Windows, which is why you may see this here and not in a standalone Command Prompt. The fix is to create the venv without pip first, then install pip separately.

First, delete the incomplete .venv that was created. Run this in the terminal — if it says the path does not exist, that is fine, just continue:
Remove-Item -Recurse -Force .venv

Then create the venv without pip:
python -m venv .venv --without-pip

Then install pip into it directly:
.venv\Scripts\python.exe -m ensurepip --upgrade

You should see Successfully installed pip-xx.x.x at the end. Once you do, open a new terminal tab inside VS Code — you should see (.venv) at the start of the prompt, which means the venv is active and you are ready to continue.

Do not use the standalone Command Prompt or Terminal after this

Once you are working in VS Code, use VS Code's built-in terminal for all commands in this lesson. If you activate the .venv in a separate Command Prompt window, those two terminals are independent — commands in one do not affect the other. Keep everything inside VS Code so the environment stays consistent.

Jupyter Notebook runs in your browser but the Python kernel behind it runs on your machine. To use a virtual environment with Jupyter you need to register it as a kernel — this takes two extra steps after creating the .venv.

Terminal — Jupyter setup
# Step 1: Navigate into your project folder, then create and activate the venv # macOS/Linux: cd ~/Documents/secure-python python3 -m venv .venv source .venv/bin/activate # Windows: # cd C:\PythonCourses\secure-python # python -m venv .venv # .venv\Scripts\activate # Step 2: Install Jupyter and ipykernel inside the venv pip install jupyter ipykernel # Step 3: Register this venv as a Jupyter kernel # Replace "secure-python" with whatever name you want to see in the kernel list python -m ipykernel install --user --name=secure-python --display-name="Secure Python" # Step 4: Launch Jupyter jupyter notebook # In the browser: when creating a new notebook, # choose "Secure Python" from the kernel list # This ensures your notebook uses the isolated venv, not system Python
Jupyter Security Note

Jupyter Notebook by default listens on localhost only, which is safe for local development. Never run jupyter notebook --ip=0.0.0.0 or expose Jupyter to the network without a password and HTTPS — this gives anyone on that network full code execution access to your machine.

Convention — always name it .venv

Regardless of which tool you use, name your virtual environment .venv. The leading dot makes it hidden in file listings, and .venv is the name recognised by VS Code, most linters, CI pipelines, and the .gitignore templates that exclude it automatically.

Knowledge Check

You are starting a new Python project. Which command correctly creates a virtual environment named .venv in the current directory?

A pip install venv .venv
B python3 -m venv .venv
C virtualenv create .venv
D python3 --venv .venv
Correct. python3 -m venv .venv uses the built-in venv module to create an isolated environment. No separate installation needed — venv ships with Python 3.3+.
Not quite. pip install venv does not create environments — pip installs packages. The correct command uses Python's built-in -m venv module flag. Try again.

What Must Never Enter Version Control

Two things must be excluded from every repository before your first commit: the .venv directory and any file that might contain secrets. Your .gitignore is a security control, not just housekeeping.

What is a .gitignore file?

A .gitignore is a plain text file that lives inside your project folder — the same folder as your .venv. It tells Git which files and folders to ignore when tracking changes. Without it, Git would try to commit thousands of files from inside your .venv and could accidentally include files containing passwords or API keys.

The file is named exactly .gitignore — starting with a dot, no other extension. You do not already have one unless you created it yourself. You need to create it now, before you do anything else with Git.

How you create the file depends on your tool. Select yours below.

Which tool are you using?

In Command Prompt, make sure you are inside your project folder, then run:

Windows — Command Prompt
type nul > .gitignore

This creates an empty .gitignore file in your project folder. Open it in any text editor — Notepad works fine — paste in the contents from the code block below, and save.

In the Terminal, make sure you are inside your project folder, then run:

macOS / Linux — Terminal
touch .gitignore

This creates an empty .gitignore file in your project folder. Open it in any text editor, paste in the contents from the code block below, and save.

Steps

1. Close the terminal panel first so you have full editor space — press Ctrl + ` (the backtick key, top-left of your keyboard above Tab) to toggle it closed, or click the X on the terminal panel. You can reopen it the same way when you need it again.

2. In the Explorer panel on the left, hover over the SECURE-PYTHON folder name — a row of icons will appear. Click the New File icon (it looks like a page with a plus sign).
3. A text box appears at the bottom of the file list. Type exactly: .gitignore and press Enter. The leading dot is required — do not skip it.
4. The file opens as a blank editor tab. If VS Code shows a "Generate code" prompt in the empty file, just click anywhere in the editor area — it disappears when you interact with the file.
5. Paste in the contents from the code block below using Ctrl+V and save with Ctrl+S.

If you do not see the New File icon, go to File → New File, paste the contents, then save with File → Save As — navigate to your secure-python folder, name it .gitignore, and click Save.

How to confirm it worked

After saving, look at the Explorer panel. Your .venv folder should now appear greyed out or with a slightly different color compared to your other files. That visual change means Git recognizes it is being ignored.

Jupyter Notebook does not have a built-in file creation tool for dotfiles. The easiest approach is to create it from the terminal that you used to launch Jupyter. Make sure you are inside your project folder and run:

Terminal — macOS / Linux
touch .gitignore
PowerShell — Windows
New-Item .gitignore

Then open the file in any text editor, paste in the contents from the code block below, and save.

gitignore .gitignore
# Virtual environment — never commit this .venv/ venv/ env/ # Environment variable files — never commit these .env .env.local .env.*.local # Python cache — not sensitive but keeps repo clean __pycache__/ *.pyc *.pyo *.pyd # Distribution and build artifacts dist/ build/ *.egg-info/
Critical Warning

If you commit .env files containing API keys, passwords, or tokens to a public repository — even for a single second — you must treat those credentials as compromised. Attackers run automated scanners on every public push. Rotating the credential is the only safe response, not deleting the file.

Dependency Pinning — What It Is and When You Will Use It

Once you start installing packages into your virtual environment, you will need a way to record exactly which versions you installed so the environment can be recreated exactly on another machine. That record is a file called requirements.txt.

You do not need to do this yet

Right now your .venv has no packages installed in it — it contains only Python itself. Running pip freeze at this point would output nothing useful. You will come back to this once you start installing real dependencies in a later lesson.

When that time comes, the workflow is:
1. Install a package: pip install requests
2. Freeze the current state: pip freeze > requirements.txt
3. Anyone else who clones your project runs pip install -r requirements.txt to get the identical environment.

This matters for security because pinning exact versions means no unexpected upgrades can silently introduce a vulnerability. A requirements.txt is an auditable record of exactly what is running.

pip-audit — coming in a later lesson

pip-audit is a tool that checks your installed packages against the Python Vulnerability Database and flags known CVEs. It belongs in your workflow every time you add a new dependency. It will be covered in depth when you have actual packages to audit — introducing it on an empty environment would produce no output and teach nothing practical.

Try It: Explore Your Python Environment

The sandbox below runs real Python via Pyodide. Use it to explore the sys module — Python's window into its own runtime environment. Try the pre-loaded code, then modify it.

The sandbox is not your local machine — this is expected

These interactive sandboxes run Python entirely inside your browser using a technology called Pyodide. No code leaves your browser and nothing runs on your computer.

Because of this, the output will look different from what you would see on your own machine in a few ways you should not worry about:

Python version: The sandbox currently runs Python 3.12. Your local installation is 3.14. That difference is normal — Pyodide has its own release cycle separate from the official Python releases. The concepts you are learning apply to both.

Executable path: The output will show something like /home/pyodide/this.program as the executable location. That is the browser sandbox environment — it is not a path on your computer and you do not need to find it or match it. When you run Python in your own terminal with your venv active, your executable path will point inside your project folder — something like C:\Users\yourname\PythonCourses\secure-python\.venv\Scripts\python.exe on Windows or /Users/yourname/Documents/secure-python/.venv/bin/python3 on macOS. If you run Python outside a venv it would point to the global installation instead, which is exactly why activating the venv matters.

Search paths: The paths shown will reference /lib/python312.zip and similar browser-side locations. Your local environment will show paths inside your .venv folder instead. This is correct.

Python Sandbox Real Python — runs in your browser
Loading Python...
Output will appear here after you run the code.
Task: First just click Run and read the output — you will see your Python version, where it is installed, and the first three paths Python searches for modules. Then, if you want to try adding code: add a new line at the bottom that prints sys.version_info.major and sys.version_info.minor to see the version numbers on their own.

▶ Need help? Show me the code
Add this line at the very bottom of the code in the sandbox, then click Run again:

print("Major:", sys.version_info.major, "Minor:", sys.version_info.minor)
This tells Python to print two values from the sys.version_info object — the major version number (3) and the minor version number (14 or similar). You will learn exactly how print() and objects like this work in the next lessons.

Try It: Check Installed Packages

The importlib.metadata module lets you inspect what packages are installed in the current environment. In a real project this would be your virtual environment — here it is the Pyodide browser environment.

Python Sandbox Modify and run freely
Waiting...
Output will appear here after you run the code.
Task: Click Run and read what the output tells you about this Python environment. Then, if you want to try extending it: add a line that checks whether this is a 64-bit or 32-bit build and prints the result.

▶ Need help? Show me the code
Add these two lines at the very bottom of the sandbox code, then click Run again:

bits = "64-bit" if sys.maxsize > 2**32 else "32-bit" print("Build:", bits)
The first line checks a number Python uses internally — on a 64-bit system it is larger than 2 to the power of 32. The result gets stored in a variable called bits. The second line prints it. You will learn how variables, if, and else work in the next lessons.
Knowledge Check

You commit a .env file containing a database password to a public GitHub repository, then immediately delete it and push again. What is the correct next action?

A Nothing — the file is deleted so the password is no longer exposed.
B Make the repository private to prevent further access.
C Rotate the credential immediately — treat it as compromised regardless of how briefly it was exposed.
D Use git rebase to remove the commit from history.
Correct. Automated scanners run continuously on public repositories and can capture a secret within seconds of a push. Deleting the file or rewriting history does not help if the secret has already been scraped. Rotate the credential immediately and assume it is in use by an attacker.
Not quite. Git history rewriting and making a repo private do not help once a secret has been exposed publicly — scrapers operate faster than humans can react. The only safe response is to rotate the credential. Review the callout box above for the full explanation.

What You Covered

Lesson Complete

Virtual environments isolate project dependencies and limit blast radius.
python3 -m venv .venv creates an isolated environment using only the standard library.
.gitignore must exclude .venv/ and all .env files before the first commit.
pip freeze pins exact dependency versions for reproducible, auditable environments.
pip-audit scans pinned requirements for known CVEs.
Exposed secrets must be rotated — deletion from git history is not sufficient.

Frequently Asked Questions

Do I need to create a new virtual environment for every project?

Yes — one virtual environment per project is the correct approach. Sharing a single environment across multiple projects defeats the purpose of isolation. If a package in a shared environment has a vulnerability or causes a conflict, every project that depends on it is affected at once.

The cost of creating a new environment is trivial: one command and a few seconds. The cost of not doing it is unpredictable version conflicts and a much larger blast radius if something goes wrong.

What happens if I forget to activate the virtual environment before installing a package?

The package installs into your global Python installation instead of your project's .venv. This creates exactly the situation virtual environments are designed to prevent: global state, version conflicts between projects, and no clean way to audit what belongs to what.

If you catch it immediately, uninstall the package globally with pip uninstall package-name, activate your .venv, then reinstall. Check that (.venv) appears in your terminal prompt before running any pip install command.

Can I commit my .venv folder to git?

No. Virtual environments are machine-specific — they contain absolute paths that point to locations on your computer. Those paths will be wrong on every other machine that clones the repository. They also contain thousands of files that bloat your repository size significantly.

The correct approach is to commit a requirements.txt file generated by pip freeze. Anyone cloning the project runs pip install -r requirements.txt to recreate the environment from scratch. Your .gitignore should always include .venv/.

Why does my terminal not show (.venv) after I activate the environment?

The two most common causes are activating from the wrong directory, and a PowerShell execution policy blocking the activation script on Windows.

First, confirm you are running the activation command from inside your project folder — the one that contains the .venv directory. If you run .venv\Scripts\activate from a different directory, it will fail.

On Windows in PowerShell, you may see a message about scripts being disabled. Run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser and try again. In Command Prompt this restriction does not apply — switching to cmd is often the simpler fix.

Is pip-audit enough to keep my dependencies secure?

pip-audit is a strong first line of defense — it checks your pinned packages against the Python Vulnerability Database and the OSV database for known CVEs. But it only knows about disclosed vulnerabilities. A malicious package that has not yet been flagged, a typosquatted package name, or a supply chain compromise at the package author level will not appear in its results.

Use pip-audit every time you add or update a dependency, keep your requirements.txt pinned to exact versions, and treat any package as a risk until you have reviewed what it does. Dependency security is a habit, not a single tool check.

Final Exam 5 questions — 80% to pass

Answer all five questions. You need four correct answers to pass. Questions are shuffled on every attempt. On passing, you can download a certificate of completion with your name on it.