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.
print("Hello, World!")
> Hello, World!
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
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
3. Install a Package
pip is Python's package manager, included automatically.
4. Run a Script
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.
name = "Alice" # str
age = 30 # int
height = 1.75 # float
is_admin = True # bool
print(type(name)) # <class 'str'>
Control Flow
if score >= 90:
print("A grade")
elif score >= 80:
print("B grade")
else:
print("Keep studying")
> B grade
Loops
for i in range(3):
print(i) # 0, 1, 2
# while loop
count = 0
while count < 3:
print(count)
count += 1
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.
fruits.append("date")
fruits[0] # "apple"
fruits[-1] # "date" (last item)
fruits[1:3] # ["banana","cherry"]
x, y = coords # unpacking
print(x) # 10.5
# Tuples are immutable — can't .append()
user["email"] = "a@b.com"
user.get("age") # 30
for k, v in user.items():
print(k, v)
# {"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.
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]
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
"""Returns a greeting string."""
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!"
*args and **kwargs
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(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 wrapper(*args, **kwargs):
print("Starting...")
result = func(*args, **kwargs)
print("Done.")
return result
return wrapper
@timer
def process():
print("Working...")
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
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
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.
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)
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
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.
def add(a, b):
return a + b
# main.py
from utils import add
add(2, 3) # 5
Key Standard Library Modules
Virtual Environments & pip
Always isolate project dependencies to avoid version conflicts between projects.
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
High-performance data structures like DataFrames for cleaning, filtering, reshaping, and analyzing tabular datasets.
Efficient multi-dimensional arrays, vectorization, and mathematical functions for high-speed scientific computing.
Industry-standard tools for predictive modeling, including classification, regression, clustering, and dimension reduction.
Powerful frameworks with automatic differentiation and GPU acceleration for training deep neural networks and AI models.
Web Development & APIs
A "batteries-included" web framework with built-in ORM, admin panel, authentication, and security features for rapid creation.
Lightweight backends suited for building high-performance RESTful APIs, with FastAPI utilizing native type hints for self-documenting code.
Web Scraping & Automation
An elegant HTTP client library to consume third-party API endpoints, download content, and dispatch web payloads.
Libraries to parse HTML/XML structures, crawl web pages, and extract data from websites for automation or research.
Data Visualization
The foundational plotting library to generate static line charts, scatter plots, bar graphs, and mathematical figures.
High-level visualization tools designed to draw beautiful statistical trends and interactive dashboards easily.
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
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
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.
with open("data.txt", "r") as f:
content = f.read()
# f is automatically closed here
Python Cheatsheet
String Methods
Returns the string in all uppercase or lowercase.
Splits into a list by separator. Default splits on whitespace.
Removes leading/trailing whitespace (or specified chars).
f-string — the modern way to format strings (Python 3.6+).
List Methods
Adds item to the end of the list.
Removes and returns item at index i. Default is last item.
.sort() mutates in-place. sorted() returns a new list.
Returns the length of any sequence or collection.
Built-in Functions
Generates a sequence of numbers lazily. Used in for loops.
Returns (index, value) pairs. Use when you need both.
Combines two iterables into pairs: [(a1,b1), (a2,b2)].
Applies func to each item. Returns a lazy iterator.
Dict Methods
Returns value or default if key missing. Safer than d[key].
Returns (key, value) pairs for iteration.
Returns view objects of keys or values.
Merges another dictionary into this one.
Python Interpreter
Write and run Python code directly in your browser. Select packages below to import scientific libraries.
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 .
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.