System Manual // Version 7.0 // Classified
This book teaches Python through seven progressive parts, each building on the last. It assumes no prior programming experience but rewards patience. By the end, you will be able to write real programs, understand the language deeply, and know where to go next.
Work through the parts in order. Type the code yourself — do not copy-paste. Muscle memory matters. When something confuses you, do not skip it; confusion is the feeling of learning.
"The only way to learn a language is to speak it badly until you speak it well."
Python is a programming language created by Guido van Rossum in 1991. It is named after Monty Python, not the snake. It emphasizes readability: code should look like pseudocode that happens to run.
Python is interpreted — a program reads and executes it line by line. It is dynamically typed — you do not declare variable types. It is high-level — you do not manage memory manually.
You will find Python in web servers, data science, automation, games, machine learning, and education.
Go to python.org and download the latest stable version (3.12 or newer). On Windows, check “Add Python to PATH.” Verify:
python --version
# Python 3.12.3
You also get pip, the package installer. For serious work, install VS Code with the Python extension.
Create hello.py:
print("Hello, world!")
Run with python hello.py. print() is a function; the text is an argument; the quotes mark a string.
print("Python is fun.")
print(2 + 2)
print("2 + 2 =", 2 + 2)
# This is a comment. Python ignores it.
"""
Multi-line string, often used as a docstring.
"""
def area(width, height):
"""Return the area of a rectangle."""
return width * height
Style rules from PEP 8: four spaces per indent; snake_case for variables and functions; PascalCase for classes; lines under 79 characters.
name = "Ada"
age = 36
height = 1.68
is_programmer = True
| Type | Example | Meaning |
|---|---|---|
int | 42 | whole number |
float | 3.14 | decimal number |
str | "hello" | text |
bool | True/False | truth value |
NoneType | None | absence of value |
print(type(42)) # <class 'int'>
print(int("42")) # 42
print(str(42)) # "42"
print(float("3.5")) # 3.5
"100" to an integer and add 50.print(7 + 3) # 10
print(7 - 3) # 4
print(7 * 3) # 21
print(7 / 3) # 2.333... (true division)
print(7 // 3) # 2 (floor division)
print(7 % 3) # 1 (remainder)
print(7 ** 3) # 343 (exponent)
Comparison: ==, !=, >, <, >=, <=. Logical: and, or, not. Assignment shortcuts: x += 5, x -= 3, x *= 2.
s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[0:3]) # Pyt
print(s[::-1]) # nohtyP
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lower()) # " hello, world! "
print("apple,banana".split(",")) # ['apple', 'banana']
print("-".join(["a", "b", "c"])) # a-b-c
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
print(f"Pi to 2 decimals: {3.14159:.2f}")
" Data Science " and print it stripped, lowercased, and reversed. Ask for a name with input() and print "Hello, NAME!".age = int(input("How old are you? "))
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
Ternary: status = "adult" if age >= 18 else "minor". Empty values ("", [], 0, None) are falsy.
for i in range(5):
print(i) # 0 1 2 3 4
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
count = 0
while count < 3:
print("count is", count)
count += 1
for n in range(10):
if n == 5:
break
if n % 2 == 0:
continue
print(n) # 1 3
while to sum the numbers from 1 to 100.fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] = "apricot"
nums = [3, 1, 4, 1, 5]
nums.sort()
nums.reverse()
nums.remove(4)
nums.pop()
nums.insert(0, 99)
letters = ["a", "b", "c", "d", "e"]
print(letters[1:4]) # ['b', 'c', 'd']
print(letters[::2]) # ['a', 'c', 'e']
squares = [x * x for x in range(5)]
evens = [x for x in range(10) if x % 2 == 0]
point = (3, 4)
x, y = point # unpacking
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # {3} intersection
print(a | b) # {1,2,3,4,5} union
print(a - b) # {1, 2} difference
person = {
"name": "Ada",
"age": 36,
"languages": ["Python", "C"]
}
print(person["name"]) # Ada
person["age"] = 37
print(person.get("job", "unknown")) # unknown
for key, value in person.items():
print(f"{key}: {value}")
squares = {x: x * x for x in range(5)}
def greet(name):
"""Return a greeting for name."""
return f"Hello, {name}!"
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9
print(power(3, 3)) # 27
def total(*args):
return sum(args)
def describe(**kwargs):
for key, value in kwargs.items():
print(f"{key}={value}")
is_even(n). Write average(numbers).class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
def __str__(self):
return f"Dog({self.name}, {self.age})"
rex = Dog("Rex", 3)
print(rex.bark()) # Rex says woof!
print(rex) # Dog(Rex, 3)
class Puppy(Dog):
def bark(self):
return f"{self.name} says yip!"
try:
n = int(input("Number: "))
print(10 / n)
except ValueError:
print("Not a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("No errors.")
finally:
print("Always runs.")
def withdraw(amount):
if amount < 0:
raise ValueError("Amount must be positive")
return amount
Common exceptions: ValueError, TypeError, KeyError, IndexError, FileNotFoundError.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("First line\n")
f.write("Second line\n")
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.rstrip())
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("Appended line\n")
# math_utils.py
def add(a, b):
return a + b
# main.py
import math_utils
print(math_utils.add(2, 3))
from math_utils import add
print(add(2, 3))
import math
print(math.sqrt(16)) # 4.0
import random
print(random.randint(1, 10))
import datetime
print(datetime.date.today())
Install third-party packages with pip install requests.
import json
data = {"name": "Ada", "age": 36}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"])
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerow(["Ada", 36])
python -m venv venv
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt
import re
text = "Call 555-1234 or 555-5678"
matches = re.findall(r"\d{3}-\d{4}", text)
print(matches) # ['555-1234', '555-5678']
replaced = re.sub(r"\d", "*", "abc123")
print(replaced) # abc***
if re.match(r"^\w+@\w+\.\w+$", "a@b.com"):
print("valid email")
Pattern cheat: . any char, \d digit, \w word char, \s space; + one+, * zero+, ? optional; ^ start, $ end.
# wordcount.py
import sys
def main():
if len(sys.argv) != 2:
print("Usage: python wordcount.py FILE")
return
with open(sys.argv[1], encoding="utf-8") as f:
text = f.read()
words = text.split()
print(f"Words: {len(words)}")
if __name__ == "__main__":
main()
import json
import os
FILE = "todo.json"
def load():
if not os.path.exists(FILE):
return []
with open(FILE) as f:
return json.load(f)
def save(items):
with open(FILE, "w") as f:
json.dump(items, f, indent=2)
def show(items):
for i, item in enumerate(items, 1):
status = "✓" if item["done"] else " "
print(f"[{status}] {i}. {item['text']}")
def main():
items = load()
while True:
print()
show(items)
cmd = input("add/show/done/quit > ").strip()
if cmd == "add":
items.append({"text": input("Text: "), "done": False})
elif cmd == "done":
n = int(input("Number: ")) - 1
if 0 <= n < len(items):
items[n]["done"] = True
elif cmd == "quit":
break
save(items)
if __name__ == "__main__":
main()
# test_math.py
import unittest
from math_utils import add
class TestAdd(unittest.TestCase):
def test_positive(self):
self.assertEqual(add(2, 3), 5)
def test_negative(self):
self.assertEqual(add(-1, 1), 0)
if __name__ == "__main__":
unittest.main()
For bigger projects, use pytest: pip install pytest, then run pytest.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
class Temperature:
def __init__(self, celsius):
self._c = celsius
@property
def celsius(self):
return self._c
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Below absolute zero")
self._c = value
Web: Flask, FastAPI, Django. Data: pandas, numpy, polars. Visualization: matplotlib, seaborn, plotly. ML: scikit-learn, PyTorch, TensorFlow. Automation: Playwright, Selenium, schedule. CLI: click, typer, rich. Async: asyncio, httpx.
Pick a domain and go deep. Breadth without depth is a hobby; depth without breadth is a trap.
Weeks 1–2: Parts 1–3, small scripts daily. Weeks 3–4: Parts 4–5, build the todo project. Weeks 5–6: Part 6, write a CLI tool for a real problem. Ongoing: Exercism, LeetCode, Advent of Code. Build one medium project and put it on GitHub.
# Variables and types
x = 10
s = "hello"
b = True
# Strings
s.upper(), s.lower(), s.strip(), s.split(",")
f"{x} and {s}"
# Lists
lst = [1, 2, 3]
lst.append(4), lst.pop(), lst[0], lst[-1], lst[1:3]
# Dicts
d = {"k": "v"}
d["k"], d.get("missing", default), d.items()
# Loops
for i in range(5): ...
while cond: ...
[x for x in lst if x > 2]
# Files
with open("f.txt") as fh: data = fh.read()
# JSON
import json
json.load(fh), json.dump(obj, fh)
# Classes
class C:
def __init__(self): ...
def method(self): ...
Automate the Boring Stuff with Python — Al Sweigart. Python Crash Course — Eric Matthes. Fluent Python — Luciano Ramalho. Effective Python — Brett Slatkin. Official docs: docs.python.org.
You have held in your hands the map of a language. But maps are not travel. The only way to know Python is to write it — badly at first, then less badly, then well. Every expert you admire wrote broken code and ran it and fixed it and wrote more.
Seven parts. Countless programs. Begin.