Module 3 · Beginner · Files, folders and the terminal

Environment variables and PATH explained

Environment variables and PATH: what they are, how to see and set them on Windows, Mac and Linux, fixing "command not found", and .env files for secrets.

By theprogrammers team · · 9 min read

You install Python, open a terminal, type python, and get 'python' is not recognized as an internal or external command on Windows, or command not found: python on a Mac. Python is installed; you can see it in your programs list. The terminal just doesn't know where to look for it. The fix involves environment variables and PATH, two ideas that confuse almost every beginner and that you'll use for the rest of your programming life.

An environment variable is a named setting that the operating system gives to every program. PATH is the most famous one: a list of folders where the terminal looks for programs. Other environment variables hold things like your user name, your home folder and, in real projects, passwords and API keys that must never be written into code.

What you need first: what is the terminal? and files, folders and file paths.

Key terms

  • Environment variable: a named value (like HOME=/home/ahana) that the operating system passes to programs.
  • PATH: an environment variable listing the folders where the shell looks for programs when you type a command.
  • Executable: a file that can be run as a program, like python.exe or git.
  • Session: one open terminal window. Some settings only last until it's closed.
  • .env file: a text file of settings and secrets for a project, loaded into environment variables when the program starts.

What is an environment variable?

When a program starts, the operating system hands it a small set of named values, a bit like the information printed on an exam hall ticket: who you are, where you sit, which centre. The program can read them whenever it needs. These are environment variables.

Some you already have:

VariableWindowsMac and LinuxHolds
Home folderUSERPROFILEHOMEC:\Users\Ahana or /home/ahana
User nameUSERNAMEUSERahana
Program search foldersPathPATHA list of folders
Temporary files folderTEMPTMPDIR (Mac)Where programs put temporary files

Names are usually written in CAPITALS. On Windows they're not case-sensitive (Path and PATH are the same); on Mac and Linux they are.

Seeing environment variables

In the terminal:

TaskMac and Linux (bash, zsh)Windows PowerShell
Show one variableecho $HOMEecho $env:USERPROFILE
Show allenvGet-ChildItem env:
Show PATHecho $PATHecho $env:Path

In Python, they're in os.environ, which works like a dictionary:

import os

print("PATH" in os.environ)
print(os.environ.get("FAVOURITE_CITY", "not set"))
True
not set

os.environ.get(name, default) returns the default if the variable doesn't exist, instead of crashing with a KeyError.

How PATH works

When you type python, the shell doesn't search your whole computer, which would take far too long. It looks through the folders listed in PATH, in order, and runs the first file called python (or python.exe on Windows) that it finds. If no folder has it, you get "command not found" or "not recognized".

PATH is one long string, with folders separated by ; on Windows and : on Mac and Linux:

Windows:     C:\Windows\system32;C:\Users\Ahana\AppData\Local\Programs\Python\Python313;...
Mac/Linux:   /usr/local/bin:/usr/bin:/bin:/home/ahana/.local/bin

Python can split it into a list. os.pathsep is the right separator for your system:

import os

folders = os.environ["PATH"].split(os.pathsep)
print(len(folders) > 0)
print(os.pathsep in (";", ":"))
True
True

Try for f in folders: print(f) yourself to see your own list; it'll be different from everyone else's.

To see which file actually runs when you type a command:

which python          # Mac and Linux

In PowerShell, use Get-Command python, and in Command Prompt, where python. If this shows nothing, the program's folder isn't on PATH.

Order matters

Because the shell uses the first match, PATH order decides which version runs when you have two installed. If an old Python's folder comes before a new one, typing python runs the old one. This is one reason a package you "just installed" sometimes can't be found: pip installed it into one Python, and python ran another.

Fixing "command not found"

The usual fixes, in order:

  1. Close and reopen the terminal. Installers often update PATH, but already-open terminals keep the old value.
  2. Check the program is really installed, and where: find its folder.
  3. Reinstall with the PATH option ticked. The Python installer for Windows has a box, "Add python.exe to PATH", on its first screen. Tick it. How to install Python walks through this.
  4. Use the launcher: on Windows, py usually works even when python doesn't, because the Python launcher installs into a folder that's already on PATH.
  5. Add the folder to PATH yourself (below).

Setting environment variables

For the current terminal session only

The variable exists until you close the window. Good for testing.

Mac and LinuxWindows PowerShell
export APP_MODE=development$env:APP_MODE = "development"
export PATH="$HOME/tools:$PATH"$env:Path = "C:\tools;" + $env:Path

Programs started from that terminal see the new value:

export GREETING="Namaste"
python -c "import os; print(os.environ['GREETING'])"
Namaste

(In PowerShell, set it with $env:GREETING = "Namaste" first.)

Permanently

  • Windows: press the Windows key, search "environment variables", open "Edit environment variables for your account", select Path, click Edit, then New, and paste the folder. Click OK on every window, then open a new terminal.
  • Mac (zsh): add the export line to the file ~/.zshrc, then open a new terminal.
  • Linux (bash): add the export line to ~/.bashrc.

Be careful editing PATH: add folders, but don't delete existing entries unless you know what they are, or other programs may stop working.

Environment variables for secrets: .env files

Real apps need secrets: database passwords, API keys for payment gateways or email services. Never write secrets into your code. Code gets shared, pushed to GitHub and copied into screenshots, and leaked keys get abused within minutes; automated bots scan GitHub for them all the time.

Instead, the app reads secrets from environment variables, which are set differently on each computer and server:

import os

os.environ["SMS_API_KEY"] = "test-key-123"      # normally set outside the code, shown here for the demo

api_key = os.environ.get("SMS_API_KEY")
if api_key is None:
    print("SMS_API_KEY is not set")
else:
    print("Key loaded, ends in", api_key[-3:])
Key loaded, ends in 123

During development, people keep these values in a .env file in the project folder:

SMS_API_KEY=test-key-123
DATABASE_URL=postgresql://localhost/shop
DEBUG=true

A library such as python-dotenv reads the file at start-up and puts each line into os.environ. Then:

  • Add .env to .gitignore so Git never uploads it.
  • Commit a .env.example file with the same names but fake values, so teammates know what to set.
  • On servers and cloud platforms, set the real values in the platform's settings or secrets manager.

Every environment variable is a string. DEBUG=true gives the text "true", not the Boolean True, so convert it: os.environ.get("DEBUG") == "true".

Where you'll meet environment variables

  • Installing tools: Python, Node.js, Java and Git all need to be on PATH.
  • Virtual environments: activating one puts its folder at the front of PATH, so python means the environment's Python. See pip and virtual environments.
  • Web apps: Django, Flask and Node apps read database URLs and keys from environment variables.
  • DevOps: Docker, GitHub Actions and cloud platforms all pass settings and secrets in as environment variables.

Common mistakes

  • Not reopening the terminal after changing PATH.
  • Putting secrets in code or uploading .env files.
  • Forgetting that values are strings, so "0" and "false" are both truthy in Python.
  • Using ; on Mac and Linux, or : on Windows, as the PATH separator.
  • Overwriting PATH instead of adding to it: export PATH=/my/tools wipes out everything else. Use export PATH="/my/tools:$PATH".

Practice

  1. Print your home folder in the terminal on your system.
Show the answer

echo $HOME on Mac and Linux, or echo $env:USERPROFILE in PowerShell. It shows something like /home/ahana or C:\Users\Ahana.

  1. You type git and get "command not found", but Git is installed in /opt/git/bin. What's wrong, and how do you fix it for the current session on Linux?
Show the answer

/opt/git/bin isn't in PATH, so the shell doesn't look there. Add it: export PATH="/opt/git/bin:$PATH". To make it permanent, add that line to ~/.bashrc.

  1. What does this print, and why?
import os
os.environ["DEBUG"] = "false"
if os.environ["DEBUG"]:
    print("Debug mode is on")
else:
    print("Debug mode is off")
Show the answer
Debug mode is on

The value is the string "false", and any non-empty string is truthy. Compare the text instead: if os.environ["DEBUG"] == "true":.

  1. Write Python that reads PORT from the environment, using 8000 as the default, and prints it as a number plus 1.
Show the answer
import os

port = int(os.environ.get("PORT", "8000"))
print(port + 1)
8001

Convert with int(), because environment variables are always strings. (If PORT is set on your machine, you'll see that value plus 1 instead.)

  1. Why should .env be in .gitignore, while .env.example is committed?
Show the answer

.env holds real secrets for your machine, which must never be shared. .env.example lists the variable names with fake values, so others know what they need to set, without exposing anything.

Key takeaways

  • Environment variables are named settings the OS passes to every program; Python reads them with os.environ.
  • PATH lists the folders the shell searches for commands, in order; the first match wins.
  • "Command not found" usually means the program's folder isn't on PATH, or the terminal needs reopening.
  • Set variables for a session with export (Mac, Linux) or $env: (PowerShell), or permanently in settings or ~/.zshrc/~/.bashrc.
  • Keep secrets in environment variables or a .env file that's never committed; values are always strings.

Frequently asked questions

What does "add Python to PATH" mean?

It means adding the folder that contains python.exe to the PATH environment variable, so that typing python in any terminal finds it. The Windows installer does this if you tick the box on its first screen.

Why does my PATH change not work?

Terminals read PATH when they start, so open a new terminal after changing it. Also check that you added the folder containing the program, not the program file itself, and that you used the right separator.

Are environment variables secure?

Safer than writing secrets in code, because they're not stored in your files or Git history. But other programs running as the same user can often read them, so production systems use dedicated secret managers for the most sensitive values.

What to learn next

  1. Install tools that land on your PATH with package managers.
  2. Use PATH in practice with pip and virtual environments.
  3. Revise the basics in terminal commands every beginner needs.