Python Get Started & VirtualEnv
Setting up a Python environment properly avoids project-dependency conflicts and keeps your global setup clean.
1. Getting Started with Python
Step 1: Verify Installation
Open your terminal (macOS/Linux) or Command Prompt/PowerShell (Windows) and run:
python --version
# or on macOS/Linux:
python3 --version
If Python is installed, it will print the version number (e.g., Python 3.12.2).
Step 2: Run Your First Script
Create a file named main.py and add the following code:
print("Hello, Python!")
Run the script from your terminal:
python main.py
Advertisement
2. Python Virtual Environments (venv)
A virtual environment is an isolated Python workspace. It allows you to install packages locally for a specific project without affecting other projects or system-wide settings.
MyProject/
│
├── .venv/ # Virtual environment folder (isolated packages)
├── main.py # Your project code
└── requirements.txt # Project dependencies
Advertisement
3. Working with venv Step-by-Step
- Navigate to Project Directory: Set up workspace location.
Open your terminal and create or enter your project folder:
mkdir my_project
cd my_project
- Create the Virtual Environment: Creates isolated directory folder.
Run thevenvmodule. This creates a folder named.venvinside your project directory containing a dedicated Python executable andpip.
python -m venv .venv
- Activate the Virtual Environment: Platform-dependent activation.
Activate the environment so installed packages route to.venv:
- macOS / Linux:
source .venv/bin/activate
- Windows (Command Prompt):
.venv\Scripts\activate.bat
- Windows (PowerShell):
.venv\Scripts\Activate.ps1
After activation, your terminal prompt will show (.venv) at the start of the command line.
- Install Packages with PIP: Manage dependencies locally.
Install third-party packages usingpip. They will be installed strictly within.venv:
pip install requests
- Deactivate Environment: Exit isolated environment.
When you are done working on your project, exit the virtual environment by running:
deactivate
Advertisement
4. Environment Management Cheatsheet
| Command | Action |
|---|---|
pip freeze > requirements.txt |
Save installed dependencies to a file |
pip install -r requirements.txt |
Install all dependencies listed in requirements.txt |
which python (macOS/Linux) |
Verify active Python executable path |
where python (Windows) |
Verify active Python executable path |