Setting Up Your Python Development Environment
Installing Anaconda and Configuring Your First Environment
General Instructions
Before you begin, please read these important guidelines:
Getting Help:
- If you encounter any issues or have questions at any point during this lab, raise your hand and contact the nearest Teaching Assistant (TA) immediately.
- Do not spend more than 5 minutes stuck on a single step. Ask for help early rather than falling behind.
- TAs are here to assist you. No question is too small or too basic.
Working Through the Lab:
- Follow the instructions in order. Do not skip sections unless instructed by your TA.
- Read each step carefully before executing commands.
- Pay attention to your operating system (Windows, macOS, or Linux) as instructions may differ.
- Test each step before moving to the next one to ensure everything is working correctly.
Important Notes:
- Take notes of any errors you encounter and the solutions that worked for you.
- Keep this document open for reference during future assignments.
- Make sure you complete the verification steps to confirm your installation is working.
- Do not leave the lab until you have a fully functional Python environment.
Lab Etiquette:
- Be patient during downloads and installations as they may take several minutes.
- Help your neighbors if they are struggling and you have completed a section.
- Keep your workspace organized and save any important files you create.
- Before leaving, ensure you can run Python code and that all required packages are installed.
Lab Overview
Duration: 1.5 hours
Objectives: By the end of this lab, you will be able to:
- Install Anaconda on your computer
- Understand and configure environment variables
- Create and manage Python virtual environments
- Run Python code and Jupyter notebooks
- Complete course assignments using your setup
Understanding the Basics
Before we start installing software, let’s understand some key concepts that will help you throughout this course.
What are Virtual Environments?
Think of a virtual environment as a separate workspace for each of your projects. Imagine you have two different projects:
- Project A needs Python 3.9 and version 1.0 of a package called “data-tools”
- Project B needs Python 3.11 and version 2.0 of the same “data-tools” package
Without virtual environments, you could only have one version installed at a time, and switching between projects would be a nightmare. Virtual environments solve this problem by creating isolated spaces where each project can have its own Python version and packages without interfering with each other.
Key benefits of virtual environments:
- Keep different projects separate and organized
- Avoid conflicts between package versions
- Make it easy to share your project setup with others
- Prevent accidentally breaking one project while working on another
Python Scripts vs Jupyter Notebooks
Python code can be written and executed in different ways. The two most common formats you’ll use are:
Python Scripts (.py files):
Python scripts are plain text files containing Python code, saved with a .py extension. They are:
- Simple text files you can edit in any text editor
- Run from start to finish in one go
- Good for automation, data processing, and final production code
- Example:
my_program.py
When you run a script, Python executes all the code from top to bottom and then exits.
Jupyter Notebooks (.ipynb files):
Jupyter Notebooks are interactive documents that combine code, text, and visualizations. They are:
- Divided into “cells” that can be run independently
- Interactive - you can run code, see results immediately, and modify your approach
- Great for data exploration, learning, and creating reports
- Can include formatted text, equations, images, and plots alongside your code
- Example:
data_analysis.ipynb
In a notebook, you can run one cell at a time, experiment with different approaches, and see the results right away. This makes them perfect for learning and data analysis.
When to use each:
- Use scripts for: homework assignments that just need final code, automated tasks, programs that run repeatedly
- Use notebooks for: exploring data, learning new concepts, creating reports with visualizations, step-by-step analysis
In this course, you may use both depending on the assignment requirements.
Part 1: Installing Anaconda
What is Anaconda?
Anaconda is a distribution of Python that comes with many pre-installed packages for data science and scientific computing. It also includes conda, a package manager that makes it easy to install additional packages and manage different environments.
Step 1: Download Anaconda
- Go to https://www.anaconda.com/download
- Choose the installer for your operating system (Windows, macOS, or Linux)
- Download the latest Python 3.x version (not Python 2.x)
Step 2: Install Anaconda
Windows Installation
- Run the downloaded
.exefile - Click “Next” through the setup wizard
- Important: On the “Advanced Installation Options” screen:
- Check “Add Anaconda3 to my PATH environment variable” (even though it’s not recommended, it makes things easier for beginners)
- Check “Register Anaconda3 as my default Python 3.x”
- Click “Install” and wait for the installation to complete (this may take 10-15 minutes)
- Click “Finish”
macOS Installation
- Open the downloaded
.pkgfile - Follow the installation prompts
- Click “Continue” and “Install”
- Enter your password when prompted
- Click “Close” when installation is complete
Linux Installation
- Open Terminal
- Navigate to the directory where you downloaded the file
- Run the following command (replace with your actual filename):
bash Anaconda3-2024.xx-Linux-x86_64.sh- Press Enter to read the license agreement, then type “yes” to accept
- Press Enter to confirm the installation location
- Type “yes” when asked to initialize Anaconda
Step 3: Verify Installation
Open a new terminal or command prompt and run:
conda --versionYou should see output like conda 24.x.x. If you get an error, proceed to the next section.
Part 2: Setting Up Environment Variables
If the conda --version command didn’t work, you need to add Anaconda to your system’s PATH.
Windows: Adding to PATH
- Press
Win + Xand select “System” - Click “Advanced system settings” on the right
- Click “Environment Variables” button
- Under “User variables”, find and select “Path”, then click “Edit”
- Click “New” and add these paths (adjust if you installed in a different location):
C:\Users\YourUsername\anaconda3C:\Users\YourUsername\anaconda3\ScriptsC:\Users\YourUsername\anaconda3\Library\bin
- Click “OK” on all windows
- Close and reopen your command prompt
- Test again with
conda --version
macOS/Linux: Adding to PATH
- Open Terminal
- Check which shell you’re using:
echo $SHELL- Edit your shell configuration file:
- If using bash:
nano ~/.bashrc - If using zsh:
nano ~/.zshrc
- If using bash:
- Add this line at the end of the file:
export PATH="$HOME/anaconda3/bin:$PATH"- Save the file (Ctrl+O, Enter, then Ctrl+X in nano)
- Reload the configuration:
source ~/.bashrc # or source ~/.zshrc- Test with
conda --version
Part 3: Creating Your First Environment
Why Use Environments?
Virtual environments let you have different versions of Python and packages for different projects. This prevents conflicts and keeps your projects organized.
Create a Course Environment
Open your terminal/command prompt and run these commands:
# Create a new environment named 'course_env' with Python 3.11
conda create -n course_env python=3.11 -yThis will take a few minutes as it downloads and installs Python.
Activate Your Environment
# Windows
conda activate course_env
# macOS/Linux
conda activate course_envYour prompt should now show (course_env) at the beginning, indicating the environment is active.
Install Essential Packages
With your environment activated, install the packages you’ll need:
# Install data science packages
conda install numpy pandas matplotlib jupyter -y
# Install additional useful packages
conda install scipy scikit-learn seaborn -yVerify Your Installation
Check that packages are installed:
# Check Python version
python --version
# Check installed packages
conda listPart 4: Running Python
Method 1: Python Interactive Shell
With your environment activated, simply type:
pythonYou’ll see the Python prompt >>>. Try some commands:
print("Hello, Python!")
x = 5 + 3
print(x)
exit()Method 2: Running Python Scripts
- Create a file called
test.pywith this content:
# test.py
print("This is my first Python script!")
# Do some calculation
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"The sum is: {total}")- Run it from the terminal:
python test.pyMethod 3: Jupyter Notebook
Jupyter notebooks are interactive documents that mix code, text, and visualizations.
- Start Jupyter:
jupyter notebook- Your browser will open automatically
- Click “New” → “Python 3” to create a new notebook
- Try this in a cell:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("My First Plot")
plt.show()- Press
Shift + Enterto run the cell
Part 5: Essential Commands Reference
Conda Environment Commands
# List all environments
conda env list
# Create new environment
conda create -n myenv python=3.11
# Activate environment
conda activate myenv
# Deactivate environment
conda deactivate
# Delete environment
conda env remove -n myenv
# Export environment (for sharing)
conda env export > environment.yml
# Create environment from file
conda env create -f environment.ymlPackage Management Commands
# Install a package
conda install package_name
# Install specific version
conda install package_name=1.2.3
# Update a package
conda update package_name
# Remove a package
conda remove package_name
# List installed packages
conda list
# Search for a package
conda search package_nameJupyter Commands
# Start Jupyter Notebook
jupyter notebook
# Start Jupyter Lab (more advanced interface)
jupyter lab
# List running notebooks
jupyter notebook list
# Stop all notebooks
jupyter notebook stopPart 6: Practice Exercise
Let’s put everything together! Complete this exercise to confirm your setup is working.
Exercise: Create and Run Your First Python Script
- Make sure your
course_envis activated - Create a new file called
hello.py - Copy this code into the file:
# hello.py - My first Python script
# Print a welcome message
print("Welcome to Python Programming!")
print("=" * 40)
# Basic arithmetic
print("\nLet's do some basic math:")
a = 10
b = 5
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
# Working with lists
print("\nWorking with a list of numbers:")
numbers = [1, 2, 3, 4, 5]
print(f"My numbers: {numbers}")
print(f"Sum of numbers: {sum(numbers)}")
print(f"Largest number: {max(numbers)}")
# Your turn - add your name
your_name = "Your Name Here" # Change this to your actual name
print(f"\nThis script was created by: {your_name}")
print("\nCongratulations! Your Python environment is working correctly!")- Before running, change “Your Name Here” to your actual name
- Run the script:
python hello.py- You should see output showing the calculations and your name
Expected Output:
Welcome to Python Programming!
========================================
Let's do some basic math:
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
Working with a list of numbers:
My numbers: [1, 2, 3, 4, 5]
Sum of numbers: 15
Largest number: 5
This script was created by: [Your Name]
Congratulations! Your Python environment is working correctly!
Congratulations! You’ve successfully set up your Python environment and run your first Python script.
Troubleshooting Common Issues
Issue: “conda: command not found”
Solution: Anaconda is not in your PATH. Go back to Part 2 and set up environment variables.
Issue: “Permission denied” errors on macOS/Linux
Solution: Add sudo before the command, or check file permissions with chmod.
Issue: Packages fail to install
Solution: Try updating conda first:
conda update conda
conda update --allIssue: Jupyter won’t start
Solution: Make sure jupyter is installed in your active environment:
conda install jupyter -yIssue: Environment activation doesn’t work
Solution: - Windows: Use Anaconda Prompt instead of regular Command Prompt - Mac/Linux: Make sure you’ve run conda init after installation
Preparation for Next Lab
Before the next lab session:
- Practice creating a new environment called
practice_env - Install
numpyandmatplotlibpackages in it - Create a simple Python script that prints your name and the current date
- Explore the Jupyter notebook interface and try creating cells with markdown text
Assignment Submission Setup
For course assignments:
- Always activate
course_envbefore starting work - Organize your work in folders by week/assignment
- Use Jupyter notebooks for assignments that require visualization
- Use
.pyscripts for pure code assignments - Include comments in your code explaining what each section does
Quick Start Checklist
Use this checklist at the start of each assignment:
Additional Resources
Questions?
If you encounter any issues during the lab, raise your hand and ask for help. Make sure you have a working setup before leaving today, as you’ll need it for all future assignments.
Lab Complete! You’re now ready to start programming in Python for this course.