Advertisement
❮ Previous: Python Intro & Installation Next: Python Package Manager ❯

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!")

Try this code ❯

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

  1. Navigate to Project Directory: Set up workspace location.
    Open your terminal and create or enter your project folder:
mkdir my_project
cd my_project

  1. Create the Virtual Environment: Creates isolated directory folder.
    Run the venv module. This creates a folder named .venv inside your project directory containing a dedicated Python executable and pip.
python -m venv .venv

  1. Activate the Virtual Environment: Platform-dependent activation.
    Activate the environment so installed packages route to .venv:
source .venv/bin/activate

.venv\Scripts\activate.bat

.venv\Scripts\Activate.ps1

After activation, your terminal prompt will show (.venv) at the start of the command line.

  1. Install Packages with PIP: Manage dependencies locally.
    Install third-party packages using pip. They will be installed strictly within .venv:
pip install requests

  1. 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
❮ Previous: Python Intro & Installation Next: Python Package Manager ❯
Advertisement