Whether you're starting your journey in programming or setting up for your university coursework, having a
proper Python environment is crucial. In this guide, we'll walk through how to install Python, manage packages
using pip
, and isolate your projects using virtual environments via venv
.
Step 1: Installing Python
Windows
- Visit the official Python website.
- Download the latest stable version (e.g., Python 3.12).
- Run the installer and check the box that says "Add Python to PATH".
- Click “Install Now” and follow the on-screen instructions.
- To verify installation, open Command Prompt and type:
python --version
macOS
- Install Homebrew if not already installed.
- Open Terminal and run:
brew install python
- Verify by typing:
python3 --version
Linux (Ubuntu/Debian)
- Open Terminal.
- Update packages:
sudo apt update
- Install Python:
sudo apt install python3 python3-pip
- Verify with:
python3 --version
Step 2: Installing pip (Python’s Package Installer)
Pip is a package manager for Python that allows you to install and manage additional libraries and dependencies
that are not part of the standard Python library. pip
usually comes pre-installed with Python 3.4+.
Verify by running:
pip --version
If it's not installed, try one of the following methods:
1. Using Python's Built-in Method
python -m ensurepip --upgrade
2. Using get-pip.py
Download and run the script:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Or:
wget https://bootstrap.pypa.io/get-pip.py
Then run it with Python:
python get-pip.py
3. Verifying the Installation
pip --version
Step 3: Creating and Using Virtual Environments
Why use virtual environments?
A virtual environment is an isolated Python environment that allows you to install packages specific to a project without affecting the global installation. It avoids conflicts and makes project management cleaner.
Creating a Virtual Environment
python -m venv myenv
This will create a folder named myenv
containing a standalone Python setup.
Activating the Virtual Environment
- Windows:
myenv\Scripts\activate
- macOS/Linux:
source myenv/bin/activate
Once activated, your terminal should show the environment name like this: (myenv)
Installing Packages with pip
pip install numpy pandas matplotlib
Freezing Requirements
To share your environment, create a requirements.txt
file:
pip freeze > requirements.txt
Installing from requirements.txt
pip install -r requirements.txt
Deactivating the Virtual Environment
deactivate
Tips and Best Practices
- Use one virtual environment per project to avoid dependency conflicts.
- Keep your Python version up-to-date, but stable (avoid beta releases).
- Use descriptive names for your environments:
venv-data-science
,venv-webapp
, etc. - Regularly back up your
requirements.txt
.
Need Help?
If you're a DTU student and need assistance, visit the DTU Python Support site or contact your nearest support assistant.
Happy Coding! 🐍
Comments
Post a Comment
Unprofessional comments will be reported.