Python Programming

The Language
That Reads Like English

Python is a high-level, interpreted programming language known for its clean, readable syntax. It's the world's most popular language for data science, automation, web development, and AI.

Think of it as pseudocode that actually runs. Python enforces readability through indentation, ships with a massive standard library, and has one of the largest package ecosystems on the planet.

# Your first Python program
print("Hello, World!")
> Hello, World!
00 / The Origins

A Holiday Project That Took Over the World

Python was born in the late 1980s as a hobby project. Guido van Rossum started writing it during the Christmas holidays while looking for a programming project to keep himself occupied.

Guido's Design Goals

  • Simple and easy to read — code should be readable like English prose.
  • Interactive top-level shell for fast experimentation.
  • Extensible — easily embed C/C++ code when speed matters.
  • Batteries included — rich standard library from day one.
"Python is an experiment in how much freedom programmers need. Too much freedom and nobody can read anyone else's code; too little and expressiveness is lost."

— Guido van Rossum

Named after Monty Python's Flying Circus, not the snake.

Timeline

1991
v0.9 released
2000
Python 2.0
2008
Python 3.0
2020+
Python 3 era
00.5 / Installation

Getting Python Running

Python runs everywhere. Select your operating system for installation instructions.

1. Download the Installer

Visit python.org/downloads and grab the latest Python 3 installer for Windows.

⚠️ Check "Add Python to PATH" during installation — this is critical.

2. Verify Installation

python --version
Python 3.x.x

3. Install a Package

pip is Python's package manager, included automatically.

pip install requests

4. Run a Script

python hello.py
01 / Core Language

Core Syntax

Python uses indentation (whitespace) to define code blocks instead of braces. This forces readable code by design.

Variables & Types

Python is dynamically typed — you don't declare types explicitly.

# No type declarations needed
name = "Alice" # str
age = 30 # int
height = 1.75 # float
is_admin = True # bool

print(type(name)) # <class 'str'>

Control Flow

score = 85

if score >= 90:
    print("A grade")
elif score >= 80:
    print("B grade")
else:
    print("Keep studying")

> B grade

Loops

# for loop with range
for i in range(3):
    print(i) # 0, 1, 2

# while loop
count = 0
while count < 3:
    print(count)
    count += 1
02 / Data Structures

Built-in Data Types

Python provides powerful built-in data structures. Understanding when to use each is one of the most important skills in the language.

list Ordered, Mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] # "apple"
fruits[-1] # "date" (last item)
fruits[1:3] # ["banana","cherry"]
tuple Ordered, Immutable
coords = (10.5, 20.3)
x, y = coords # unpacking
print(x) # 10.5

# Tuples are immutable — can't .append()
dict Key-Value, Ordered (3.7+)
user = {"name": "Alice", "age": 30}
user["email"] = "a@b.com"
user.get("age") # 30
for k, v in user.items():
    print(k, v)
set Unordered, Unique
tags = {"python", "code", "python"}
# {"python", "code"} — duplicates removed

a = {1, 2, 3}
b = {2, 3, 4}
a & b # {2, 3} — intersection
a | b # {1,2,3,4} — union

List Comprehensions

One of Python's most loved features — a concise way to build lists.

# Traditional loop
squares = []
for x in range(5):
    squares.append(x ** 2)

# List comprehension (same result)
squares = [x ** 2 for x in range(5)]
> [0, 1, 4, 9, 16]

# With a filter
evens = [x for x in range(10) if x % 2 == 0]
> [0, 2, 4, 6, 8]
03 / Functions

Defining & Using Functions

Functions are first-class objects in Python — you can assign them to variables, pass them as arguments, and return them from other functions.

Basic Functions

def greet(name, greeting="Hello"):
    """Returns a greeting string."""
    return f"{greeting}, {name}!"

greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!"

*args and **kwargs

def total(*numbers):
    return sum(numbers)

total(1, 2, 3) # 6

def profile(**data):
    print(data)

profile(name="Alice", age=30)
> {'name': 'Alice', 'age': 30}

Lambda Functions

Anonymous, single-expression functions for quick operations.

square = lambda x: x ** 2
square(5) # 25

nums = [3, 1, 4, 1, 5]
sorted(nums, key=lambda x: -x)
> [5, 4, 3, 1, 1]

Decorators

A decorator wraps a function to add behavior without modifying it — used extensively in frameworks like Flask and Django.

def timer(func):
    def wrapper(*args, **kwargs):
        print("Starting...")
        result = func(*args, **kwargs)
        print("Done.")
        return result
    return wrapper

@timer
def process():
    print("Working...")
04 / Object Oriented

Object-Oriented Programming

Python supports OOP with classes, inheritance, encapsulation, and polymorphism. Everything in Python is an object, including functions, modules, and even types themselves.

Classes & Instances

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def speak(self):
        return f"{self.name} makes a sound"

dog = Animal("Rex", "Dog")
print(dog.name) # Rex
print(dog.speak()) # Rex makes a sound

Inheritance

class Dog(Animal):
    def speak(self):
        return f"{self.name} says: Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says: Meow!"

# Polymorphism in action
for animal in [Dog("Rex","Dog"), Cat("Mimi","Cat")]:
    print(animal.speak())
> Rex says: Woof!
> Mimi says: Meow!

Special Methods (Dunder)

Python's "magic methods" let you customize how objects behave with built-in operators.

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2); v2 = Vector(3, 4)
v1 + v2 > Vector(4, 6)
05 / Ecosystem

Modules & Packages

Python's "batteries included" philosophy means there's a module for almost everything in the standard library. The PyPI ecosystem adds hundreds of thousands more.

Importing Modules

import math
math.sqrt(16) # 4.0

from datetime import datetime
datetime.now() # current date & time

import json as j # aliasing
j.loads('{"key": "val"}')

Creating Your Own Module

Any .py file is a module. Group modules in folders with an __init__.py to make a package.

# utils.py
def add(a, b):
    return a + b

# main.py
from utils import add
add(2, 3) # 5

Key Standard Library Modules

os
File system operations, env variables
sys
Interpreter state, command-line args
json
Encode/decode JSON data
re
Regular expressions
datetime
Date and time objects
collections
Counter, defaultdict, deque

Virtual Environments & pip

Always isolate project dependencies to avoid version conflicts between projects.

python -m venv .venv
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
pip install -r requirements.txt

Popular External Libraries & Use Cases

Python's extensive package ecosystem (via PyPI) allows you to import third-party libraries for specialized domains. Below are some of the most widely used libraries and their core use cases:

Data Science & Machine Learning
pandas Data Analysis

High-performance data structures like DataFrames for cleaning, filtering, reshaping, and analyzing tabular datasets.

numpy Numerical Ops

Efficient multi-dimensional arrays, vectorization, and mathematical functions for high-speed scientific computing.

scikit-learn Machine Learning

Industry-standard tools for predictive modeling, including classification, regression, clustering, and dimension reduction.

pytorch / tensorflow Deep Learning

Powerful frameworks with automatic differentiation and GPU acceleration for training deep neural networks and AI models.

Web Development & APIs
Django Full-Stack Web

A "batteries-included" web framework with built-in ORM, admin panel, authentication, and security features for rapid creation.

Flask / FastAPI Micro-services & APIs

Lightweight backends suited for building high-performance RESTful APIs, with FastAPI utilizing native type hints for self-documenting code.

Web Scraping & Automation
requests HTTP requests

An elegant HTTP client library to consume third-party API endpoints, download content, and dispatch web payloads.

beautifulsoup4 / scrapy Data Harvesting

Libraries to parse HTML/XML structures, crawl web pages, and extract data from websites for automation or research.

Data Visualization
matplotlib Static Plots

The foundational plotting library to generate static line charts, scatter plots, bar graphs, and mathematical figures.

seaborn / plotly Statistical & Interactive

High-level visualization tools designed to draw beautiful statistical trends and interactive dashboards easily.

06 / Resilience

Error Handling & Exceptions

Python uses try/except blocks to handle errors gracefully. Writing code that fails well is as important as code that succeeds.

try / except / finally

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError):
    print("Type or value issue")
else:
    print("No errors!") # runs if no exception
finally:
    print("Always runs")

> Error: division by zero
> Always runs

Custom Exceptions

class InsufficientFundsError(Exception):
    def __init__(self, amount):
        super().__init__(f"Need ${amount} more")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(amount - balance)
    return balance - amount

Context Managers (with)

The with statement ensures resources are properly cleaned up.

# File always closes, even if an error occurs
with open("data.txt", "r") as f:
    content = f.read()

# f is automatically closed here
07 / Reference

Python Cheatsheet

String Methods

str.upper() / .lower()

Returns the string in all uppercase or lowercase.

str.split(sep)

Splits into a list by separator. Default splits on whitespace.

str.strip() / .lstrip() / .rstrip()

Removes leading/trailing whitespace (or specified chars).

f"{variable}"

f-string — the modern way to format strings (Python 3.6+).

List Methods

list.append(x)

Adds item to the end of the list.

list.pop(i)

Removes and returns item at index i. Default is last item.

list.sort() / sorted()

.sort() mutates in-place. sorted() returns a new list.

len(x)

Returns the length of any sequence or collection.

Built-in Functions

range(start, stop, step)

Generates a sequence of numbers lazily. Used in for loops.

enumerate(iterable)

Returns (index, value) pairs. Use when you need both.

zip(a, b)

Combines two iterables into pairs: [(a1,b1), (a2,b2)].

map(func, iterable)

Applies func to each item. Returns a lazy iterator.

Dict Methods

dict.get(key, default)

Returns value or default if key missing. Safer than d[key].

dict.items()

Returns (key, value) pairs for iteration.

dict.keys() / .values()

Returns view objects of keys or values.

dict.update(other)

Merges another dictionary into this one.

07.5 / Interactive Playground

Python Interpreter

Write and run Python code directly in your browser. Select packages below to import scientific libraries.

Libraries:
Lazy (Not Loaded)
code_editor.py
1

                                    
                                

For a more powerful experience with full library support (numpy, pandas, matplotlib, scikit-learn, seaborn, scipy, sympy) and dedicated plotting, use the Python Interpreter Visualab .

Glossary

Key Definitions

Interpreter

Python is interpreted, not compiled. Code is executed line by line by the CPython runtime (or PyPy, Jython, etc.).

Dynamic Typing

Variable types are determined at runtime, not at compile time. A variable can be rebound to a different type.

GIL (Global Interpreter Lock)

A mutex in CPython that prevents multiple threads from executing Python bytecode simultaneously. Affects CPU-bound multithreading.

Iterable

Any object with an __iter__ method: lists, strings, dicts, generators. Can be used in a for loop.

Generator

A function that uses yield to produce a lazy sequence. Memory-efficient for large datasets.

Decorator

A higher-order function that wraps another function to extend behavior without modification. Used with @syntax.

Mutable vs Immutable

Mutable objects (list, dict, set) can be changed. Immutable objects (str, tuple, int) cannot. This affects how they're passed and shared.

Dunder Methods

Special methods surrounded by double underscores (__init__, __str__, __add__) that Python calls for built-in operations.

pip

Python's package installer. Installs packages from PyPI (the Python Package Index).

Virtual Environment (venv)

An isolated Python environment with its own packages, separate from the system Python. Best practice for every project.

08 / Knowledge Check