Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module Overview

Python Fundamentals | Modeling the Universe

San Diego State University

Your Computational Toolkit for Astrophysics

You’ve set up your environment and mastered Git—now it’s time to build your Python foundation for computational astrophysics. This module provides the essential tools and patterns you’ll use throughout the course, from basic numerical operations to object-oriented design for complex simulations.

Module Overview

📊 Chapter 1: Computational Environments & Scientific Workflows

Master IPython, understand how Python finds code, avoid Jupyter’s hidden traps, and create reproducible computational environments

🔢 Chapter 2: Python as Your Astronomical Calculator

Discover why 0.1 + 0.2 ≠ 0.3, handle extreme astronomical scales, and learn numerical safety that prevents spacecraft crashes

🔀 Chapter 3: Control Flow & Logic

Design algorithms with pseudocode, implement conditional logic, master loops, and build the patterns that power every simulation

🗂️ Chapter 4: Data Structures - Organizing Scientific Data

Choose between O(1) and O(n) operations, understand memory layout, and architect data organization for million-particle simulations

🔧 Chapter 5: Functions & Modules - Building Reusable Scientific Code

Create clear functional contracts, understand scope and namespaces, organize code into modules, and build professional scientific libraries

🎯 Chapter 6: OOP Fundamentals - Organizing Scientific Code

Transform functions and data into cohesive classes, understand when objects improve code organization, and model scientific concepts naturally

Learning Strategy

Build Through Practice

These chapters work best when you:

  1. Skim first to see what’s available

  2. Dive deep when you hit a specific problem

  3. Return often as you work on assignments

  4. Run the code examples in IPython as you read

  5. Modify examples to test your understanding

The Variable Star Thread

Quick Navigation Guide

“I need to...” → “Go to...”

When you need to...Check this chapter...Look for section on...
Fix ModuleNotFoundErrorCh 1: EnvironmentsImport System, Debug Import Problems
Compare floating-point numbersCh 2: CalculatorSafe Floating-Point Comparisons
Break out of a loop earlyCh 3: Control FlowLoop Control: break, continue
Speed up particle lookupsCh 4: Data StructuresDictionaries: O(1) Lookup Magic
Avoid mutable default bugCh 5: FunctionsThe Mutable Default Trap
Handle numerical overflowCh 2: CalculatorOverflow and Underflow
Design before codingCh 3: Control FlowAlgorithmic Thinking: Pseudocode
Cache expensive calculationsCh 4: Data StructuresDictionaries for Caching
Bundle data with behaviorCh 6: OOPClasses and Objects
Validate with propertiesCh 6: OOPProperties: Smart Attributes

Common Patterns You’ll Use Constantly

Defensive Programming (appears everywhere)

# From Chapter 1: Always validate
assert len(data) > 0, "Cannot process empty data"

# From Chapter 2: Check numerical bounds
if not math.isfinite(value):
    raise ValueError(f"Invalid result: {value}")

Safe Numerical Comparisons (critical for simulations)

# From Chapter 2: Never use == with floats
if math.isclose(calculated, expected, rel_tol=1e-9):
    print("Converged!")

Efficient Lookups (essential for large datasets)

# From Chapter 4: O(1) vs O(n) matters!
# Slow: searching a list
if particle_id in particle_list:  # O(n)
    
# Fast: dictionary lookup  
if particle_id in particle_dict:  # O(1)

Object-Oriented Design (managing complex state)

# From Chapter 6: Bundle data with behavior
class Particle:
    def __init__(self, mass, position):
        self.mass = mass
        self.position = position
    
    def update_position(self, dt):
        self.position += self.velocity * dt

Your Reference Checklist

As you work through the chapter exercises and course assignments, you’ll naturally master these concepts:

Core Competencies

Numerical Safety

Algorithm Design

Data Organization

Code Structure

Problem-Solving Flowchart

Homework Problem
    ↓
"What kind of problem is this?"
    ├─ Numerical precision issue → Chapter 2
    ├─ Need to repeat operation → Chapter 3 (loops)
    ├─ Organizing many items → Chapter 4 (data structures)
    ├─ Code getting repetitive → Chapter 5 (functions)
    ├─ Managing complex state → Chapter 6 (classes)
    └─ Import not working → Chapter 1 (environments)

Performance Quick Reference

Keep this table handy when choosing data structures:

OperationListDictSetYour Choice When...
Find by IDSlow O(n)Fast O(1)Fast O(1)You have unique IDs → Dict
Keep order✓ Yes✗ No✗ NoOrder matters → List
No duplicates✗ Manual✗ Manual✓ AutomaticUnique items → Set
By positionFast O(1)✗ No✗ NoNeed indexing → List

What’s Next?

After building your Python foundation with all six chapters, you’ll advance to Scientific Computing Core where these fundamentals become powerful tools:

The patterns you learn here—defensive programming, algorithmic thinking, performance awareness — will guide you through increasingly sophisticated computational challenges.


Ready to build your toolkit? Start exploring Chapter 1: Computational Environments & Scientific Workflows

Remember: These chapters are your companions throughout the course. Bookmark them, return often, and use them actively as you solve real problems!