Modules, pip and virtual environments
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- Project: summaries, search and improvements
You do not have to write everything
Python comes with a large standard library: tools for dates, random numbers, JSON, files and much more. Beyond that, other developers publish thousands of packages that you can install for free. Both are used through import.
Importing from the standard library
import random
import datetime
from pathlib import Path
from collections import Counter
today = datetime.date.today()
print(f"Today is {today:%d %B %Y}")
print(random.choice(["tea", "coffee", "juice"]))
votes = ["tea", "coffee", "tea", "tea", "juice", "coffee"]
print(Counter(votes).most_common(1)) # [('tea', 3)]
print(Path.home())
There are two styles. import random makes the module available and you write random.choice(...). from collections import Counter brings one name straight in, so you write just Counter. The first style makes it clear where each name comes from, so I prefer it for short module names. Avoid from module import *. It dumps unknown names into your file and hides where things come from.
Making your own module
Any .py file is a module. Create a file called pricing.py:
# pricing.py
TAX_RATE = 0.17
def with_tax(amount):
return round(amount * (1 + TAX_RATE), 2)
if __name__ == "__main__":
print(with_tax(1000)) # runs only when you execute pricing.py directly
In another file in the same folder, import it:
# shop.py
import pricing
print(pricing.with_tax(2500)) # 2925.0
The if __name__ == "__main__": block is a standard idiom. When you run a file directly, Python sets __name__ to "__main__". When the file is imported, __name__ is the module name instead. So the test code in that block runs only when you run the file itself, not when you import it.
Do not name your own file the same as a standard library module. A file called random.py in your project will be imported instead of the real one, and you will see strange errors.
Installing packages with pip
The Python Package Index (PyPI) holds third-party packages. The tool that installs them is pip, and it comes with Python. For example, requests is a friendly library for web requests.
But do not install packages globally. Different projects need different versions, and they will clash. The fix is a virtual environment: a private folder with its own copy of Python and its own packages for one project.
Creating a virtual environment
In your project folder, run:
python -m venv .venv
Now activate it. On Windows PowerShell:
.venv\Scripts\Activate.ps1
On macOS and Linux:
source .venv/bin/activate
Your prompt now starts with (.venv). If PowerShell refuses with an execution policy error, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, then try again.
Install a package and use it:
pip install requests
pip list
pip freeze > requirements.txt
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
pip freeze lists every installed package with its exact version. Saving that to requirements.txt lets someone else (or you, on another computer) recreate the same setup with pip install -r requirements.txt. When you are finished, type deactivate to leave the environment.
Common mistakes
- Installing without activating. The package goes into the global Python, and your project cannot find it, or worse, finds the wrong version. Check for
(.venv)in the prompt. - Committing .venv to Git. It is large and specific to your machine. Add
.venv/to.gitignoreand commitrequirements.txtinstead. - ModuleNotFoundError. Usually a package is not installed in the environment you are running, or your editor is using a different interpreter than your terminal. In VS Code, pick the interpreter inside
.venv. - Using the wrong pip. Run
python -m pip install ...to be sure pip belongs to the same Python you will run.
Try it yourself
Create a new folder, make a virtual environment and activate it. Install requests. Write a module greetings.py with a function greet(name) that returns a greeting, and a main.py that imports and uses it. Finally run pip freeze and look at the list. Notice that requests brings other packages with it.
import random
import datetime
from pathlib import Path
from collections import Counter
today = datetime.date.today()
print(f"Today is {today:%d %B %Y}")
print(random.choice(["tea", "coffee", "juice"]))
votes = ["tea", "coffee", "tea", "tea", "juice", "coffee"]
print(Counter(votes).most_common(1)) # [('tea', 3)]
print(Path.home())
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account