In this unit you install a current Python, learn the three ways you will run code (the interactive prompt, scripts and python -m), pick an editor, and create a virtual environment: a private, per project Python installation that keeps each project's packages separate.
Setting up a virtual environment on day one may feel early, but it saves you from the most common beginner problems: packages that install "somewhere else", projects that break each other, and the externally-managed-environment error on Linux and macOS.
You will be able to:
- Install Python 3.13 or newer on Windows, macOS or Linux and check which version you have
- Use the interactive interpreter (the REPL) and
help()to try code and read documentation - Run a script from a terminal, and run a library module with
python -m - Create, activate and deactivate a virtual environment, and install a package into it
- Explain the "externally-managed-environment" error and why a virtual environment avoids it
Which command runs Python?
The command name depends on your operating system, and you will see all of these in documentation:
| System | Command | Notes |
|---|---|---|
| Windows | py or python | py is the Python install manager's command and can pick between versions |
| macOS and Linux | python3 | python may be missing or may be something else; use python3 outside a virtual environment |
| Any system, inside an activated virtual environment | python | Always the environment's own interpreter |
This course writes python in commands that work inside an activated virtual environment, which is where you should run almost everything.
Installing Python
You need Python 3.13 or newer. Every example in this course was tested on CPython 3.15.
Windows
The documentation now recommends the Python install manager (PEP 773). You can get it from python.org/downloads or from the Microsoft Store; the documentation says the two are identical. It gives you the commands py, python and pymanager, and it installs and updates Python versions for you.
If no runtime is installed yet, the first python or py command installs the latest release automatically.
Note. The traditional full installer (
python-3.x.y-amd64.exe) still exists but is deprecated since 3.14, and the documentation says it won't be produced for 3.16 or later. If you have used it before, it works; for a new machine, use the install manager.
Pitfall. If typing
pythonopens the Microsoft Store or says the command isn't found, open Windows Settings, search for Manage app execution aliases, and check that the "Python (default)" aliases are switched on. Then open a new terminal.
macOS
You have two good options:
- The python.org installer. You can download the macOS package from python.org/downloads and run it. It installs the
python3command. The new Python folder in Applications contains a script called Install Certificates.command. It is worth running once, so that HTTPS downloads from Python can verify certificates. - Homebrew. If you already use Homebrew, run
brew install pythonfor its current default version, or name a version, for examplebrew install python@3.14.
Note. macOS may offer a
python3that comes with Apple's developer tools. It is usually older than the current release, so install your own with one of the options above.
Linux
Most distributions already include Python 3, because system tools depend on it. You can install the extra pieces with the package manager. On Debian and Ubuntu:
sudo apt update refreshes the list of available packages; it doesn't upgrade Python by itself. On Debian and Ubuntu the ability to create virtual environments with pip inside them comes in the separate python3-venv package. Without it, python3 -m venv stops with an error that mentions ensurepip.
On Fedora, use sudo dnf install python3. Other distributions have equivalent packages.
Pitfall. Never remove or replace your distribution's
python3; parts of the operating system rely on it. If its version is older than 3.13, use a newer distribution release or a tool that installs separate Python versions alongside it (see Packaging and tooling).
Checking your version
After installing, you can check the result in a new terminal. On Windows, the Start menu finds one when you type PowerShell or Terminal. On macOS, Terminal opens from Spotlight. On Linux, it is your terminal app. One of these commands shows the version:
You should see something like Python 3.15.2. If the version is older than 3.13, or the command isn't found, fix that before you go on.
The interactive interpreter
Running py, python or python3 with no arguments starts the interactive interpreter, also called the REPL (read, eval, print loop). It reads a line, runs it and prints the result, which makes it ideal for quick experiments. The prompt >>> waits for a statement, and ... means Python expects more lines, for example the body of a loop:
A few things to notice:
- In the REPL you don't need
print()to see the value of an expression. It shows the value's representation, which is why the string appears with quotes. - An empty line ends a multiline block such as the
forloop. exitleaves the REPL. On macOS and Linux, Ctrl+D also works.
Python 3.13 introduced a new default REPL with:
- coloured prompts and tracebacks;
- multiline editing: the up arrow recalls a whole block, which you can then edit;
exit,quitandhelpthat work without parentheses;- F1 for help browsing, F2 for history without the prompts, and F3 for a "paste mode" that makes pasting larger blocks easier.
Python 3.14 added syntax highlighting and autocompletion of module names after import. If the new REPL misbehaves in an unusual terminal, setting the environment variable PYTHON_BASIC_REPL brings back the old one.
Tip. The REPL is for trying things out. Anything you want to keep belongs in a
.pyfile.
Getting help
The built in help() function shows the documentation of any object:
In a terminal, long help texts open in a pager: use the arrow keys or Space to scroll and press q to return. Other useful forms:
help(str.split)documents one method;help("keywords")lists Python's reserved words;help()with no argument starts an interactive help system with its ownhelp>prompt; typequitto leave it;dir("some text")lists the attributes and methods a value has.
For longer reading, the official tutorial and the library reference at docs.python.org are the authoritative sources.
Running scripts
A script is a text file of Python code with the extension .py. To try one, you can create a file called hello.py with this content:
print() accepts any number of values. It separates them with sep (a space by default) and finishes with end (a newline by default). Its file parameter defaults to None, which means standard output.
To run the script, open a terminal, change to the folder that contains it with cd (for example cd Documents/python-course), and pass the file name to Python:
A script can ask the user for text with input(). It shows a prompt, waits for a line and returns it as a string. The first line of the example, # Input: Grace, records what was typed at the prompt:
In a terminal it looks like this, with your typing after the prompt:
input() always returns a str, even when the user types digits. The Values, names and types unit shows how to convert it.
Running modules with python -m
python -m name finds the module name on Python's import path and runs it as a script. Many tools in the standard library are used this way:
| Command | What it does |
|---|---|
python -m venv .venv | Create a virtual environment in the folder .venv |
python -m pip install requests | Run pip, the package installer, for this interpreter |
python -m json.tool data.json | Pretty print a JSON file |
python -m http.server --bind 127.0.0.1 8000 | Serve the current folder at http://127.0.0.1:8000 |
python -m timeit "sum(range(1000))" | Time a small piece of code |
python -m this | Print the Zen of Python |
Why python -m pip rather than plain pip? If you have several Pythons installed, a bare pip command may belong to a different one than the python you run. python -m pip always installs into the interpreter you named. This course uses it everywhere.
Pitfall.
python -m http.serverwithout--bindlistens on all network interfaces, so other machines on your network may be able to read the folder. Bind it to127.0.0.1and never serve a folder that holds secrets.
Choosing an editor
Any editor that saves plain UTF-8 text works, but two are especially well supported:
- Visual Studio Code with Microsoft's Python extension. It adds syntax checking, autocompletion, debugging and test running. Its command Python: Select Interpreter lets you pick your project's virtual environment; it usually finds a
.venvfolder in the project on its own. - PyCharm from JetBrains, a full Python IDE with a free tier. It offers to create a virtual environment when you start a new project.
Most Python installations also include IDLE, a small editor that is enough for the first few units; on Linux it is often a separate package.
Whichever you choose, configure it to indent with 4 spaces (never tabs) and to save files as UTF-8. The Packaging and tooling unit adds automatic formatting and linting.
Virtual environments from day one
A virtual environment (often shortened to venv) is a folder that contains its own python command and its own site-packages folder for installed packages. It reuses the standard library of the Python you created it from, so it is small and quick to make. Packages installed into one environment don't affect any other project or the system Python.
The workflow is always the same:
Create
You can run this in your project folder. .venv is the conventional name:
Activate
Activating changes your current terminal session so that python and pip refer to the environment. The command depends on your shell:
| Shell | Command |
|---|---|
| Windows Command Prompt (cmd) | .venv\Scripts\activate.bat |
| Windows PowerShell | .venv\Scripts\Activate.ps1 |
| bash or zsh (macOS, Linux) | source .venv/bin/activate |
| fish | source .venv/bin/activate.fish |
Your prompt now starts with (.venv).
Note. On Windows, PowerShell may refuse with a message saying that running scripts is disabled on this system. The Python documentation suggests allowing local scripts for your user account only, which you need to do once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
RemoteSignedlets scripts created on your machine run, while scripts downloaded from the internet still need a signature. If you'd rather not change the policy, use Command Prompt andactivate.batinstead.
Install a package
With the environment active, python is the environment's interpreter, so the same commands work on every system:
pip list shows requests and the packages it depends on, all inside .venv. Nothing outside the project changed.
Deactivate
The prompt loses its (.venv) prefix and python means the system interpreter again.
Good habits
- One environment per project, inside the project folder.
- Don't commit it to version control. Since 3.13,
venvwrites a.gitignoreinside the environment so Git ignores it automatically. - Don't move or copy it. Environments contain absolute paths. It is safer to record your dependencies (the Packaging and tooling unit shows how) and recreate the environment instead.
- Activation is optional. You can run the environment's interpreter by its path:
.venv\Scripts\python.exeon Windows or.venv/bin/pythonon macOS and Linux.
"externally-managed-environment" (PEP 668)
On recent Debian and Ubuntu releases, several other Linux distributions and Homebrew on macOS, this happens when you try to install a package into the system Python:
This is deliberate. PEP 668 lets a distribution mark its Python as externally managed, meaning its packages belong to the operating system's package manager. If pip overwrote them, system tools written in Python could break.
The fix is the habit you have already learned: create and activate a virtual environment, then install there. The environment isn't marked as externally managed, so pip works normally. For command line tools that you want everywhere, use pipx instead (see Packaging and tooling).
Pitfall. pip offers a
--break-system-packagesoption to override the protection. As the name says, it can break your system. You don't need it for anything in this course.
Check your setup
You can save this as check_setup.py and run it inside your activated environment. Your output will differ, because it reports your own installation:
On a Linux machine inside a virtual environment, the output might be:
What each line tells you:
- Version must be 3.13 or newer.
- Interpreter is the full path of the Python that ran the script. Inside an environment it points into
.venv. - In a venv compares
sys.prefix, the folder of the running environment, withsys.base_prefix, the folder of the Python it was created from. They differ only inside a virtual environment. - UTF-8 mode is
1by default from Python 3.15 (PEP 686): text files, standard input and output use UTF-8 regardless of your system's locale. On 3.13 and 3.14 you will usually see0. Either way, this course always passesencoding="utf-8"when it opens a file, so the code behaves the same on every version; Text, bytes and Unicode explains why.
Check yourself
- Which command checks the Python version on Windows, and which on macOS or Linux?
- What do the
>>>and...prompts mean in the REPL? - Why does this course write
python -m pip install ...instead ofpip install ...? - What does activating a virtual environment change, and what does
deactivatedo? - You get "running scripts is disabled on this system" in PowerShell when activating. What are your two options?
- Why do Debian and Ubuntu refuse
pip installinto the system Python, and what should you do instead? - How can a script find out whether it is running inside a virtual environment?
- Should you commit
.venvto Git or copy it to another computer?
Suggested answers
py --version(orpython --version) on Windows;python3 --versionon macOS and Linux.>>>waits for a new statement;...means the current statement continues, for example inside a loop body. An empty line ends the block.python -m pipruns pip for exactly that interpreter, so packages go where you expect even with several Pythons installed.- It changes the current terminal session so that
pythonandpiprefer to the environment's copies; the prompt shows(.venv).deactivateundoes that. - Allow local scripts for your user with
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser, or use Command Prompt with.venv\Scripts\activate.bat. You can also skip activation and run.venv\Scripts\python.exedirectly. - Their Python is marked as externally managed (PEP 668), because pip could overwrite packages the operating system depends on. Create a virtual environment and install there, or use
pipxfor command line tools. - Compare
sys.prefixwithsys.base_prefix: they differ only inside a virtual environment. - No. It contains absolute paths and is easy to rebuild; record the dependencies and recreate it. Since 3.13 it even contains a
.gitignorethat keeps it out of Git.
Exercises
These exercises are optional practice. Pick the ones that help you.
As in the previous unit, the solutions wrap answers in small functions so they can be tested with assert. They also use if, loops and try, which Control flow and Errors and exceptions explain. Copy the pattern for now; the point of these exercises is the setup itself.
- Centred title. Use
help(str.center)in the REPL to find out what its arguments do. Then print the wordPythoncentred in a field 20 characters wide, padded with*. Expected output:*******Python*******. - One call each. With a single
print()call each, print the numbers2026,11and11as2026-11-11, and the wordsred,greenandblueasred, green, blue.(with a full stop at the end). - Which activation command? Write
activate_command(shell, venv=".venv")that returns the command to activate an environment for the shells"cmd","powershell","bash","zsh"and"fish". For example,activate_command("powershell")returns.venv\Scripts\Activate.ps1. RaiseValueErrorfor any other shell. - Base or virtual? Write
describe_interpreter(version, prefix, base_prefix)whereversionis a tuple such as(3, 15, 2). It returns"Python 3.15 (virtual environment)"when the two prefixes differ and"Python 3.15 (base installation)"when they are equal. - Version gate. Write
version_problem(version, minimum=(3, 13))that returnsNonewhenversion(a tuple such as(3, 15, 2)) is at leastminimum, and otherwise a message such as"Python 3.13 or newer is required; this is 3.12.". Tuples compare item by item, so(3, 12, 9) < (3, 13)isTrue.
Solutions
1. Centred title.
The six letters leave 14 spaces to fill, so center puts 7 fill characters on each side.
2. One call each.
If you replace end, include the newline yourself; otherwise the next output continues on the same line.
3. Which activation command?
In a normal string, a backslash starts an escape sequence, so "\\" stands for one backslash.
4. Base or virtual?
5. Version gate.
tuple(version) lets the function accept a list such as [3, 15, 2] as well. A plain tuple and sys.version_info already compare correctly without it.