惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
U
Unit 42
美团技术团队
NISL@THU
NISL@THU
C
Cisco Blogs
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Cloudbric
Cloudbric
雷峰网
雷峰网
T
Tailwind CSS Blog
博客园 - 司徒正美
The Register - Security
The Register - Security
L
LangChain Blog
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Threat Research - Cisco Blogs
I
InfoQ
S
Schneier on Security
L
Lohrmann on Cybersecurity
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Martin Fowler
Martin Fowler
Schneier on Security
Schneier on Security
F
Fortinet All Blogs
TaoSecurity Blog
TaoSecurity Blog
K
Kaspersky official blog
Google DeepMind News
Google DeepMind News
Cisco Talos Blog
Cisco Talos Blog
PCI Perspectives
PCI Perspectives
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
Project Zero
Project Zero
The GitHub Blog
The GitHub Blog
D
Docker
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Hacker News: Front Page
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
Webroot Blog
Webroot Blog
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why I Teach Python With a City Simulator (And Why You Should Build One Too)
Robert Lear · 2026-05-17 · via DEV Community

There's a wall that nobody warns you about.

You finish a Python basics course. You understand variables, loops, functions, maybe classes. You open a blank file, ready to build something real.

And nothing happens.

Not because you're bad at this. Because the jump from "I understand the concepts" to "I can build something" is itself a skill — and it's one that almost no tutorial teaches.

Tutorials teach decomposition: here is a loop, here is a function, here is a class. The implicit promise is that once you've collected enough topics, you'll be able to assemble them into something real. But assembly is a skill. And the only way to learn it is to build something that grows over a long arc, accumulates history, and fights back.

The question is: what do you build?

Not a todo list. Not a temperature converter. Something with stakes. Something where the decision you make in week two still matters in week six.

My answer: a simulation.


What Makes a Simulation Different

Most beginner projects have a simple shape: input goes in, output comes out, the program stops. A simulation has a completely different shape: it has state that persists, rules that transform that state over time, and events that keep it from being predictable.

Those three ingredients turn out to be exactly what you need to learn the things tutorials can't teach.

State is the set of values that describe your system at a given moment. A treasury balance. The condition of each building. The morale of each citizen. The day counter. Everything the simulation needs to know to continue from where it is.

Rules are the logic that transforms state over time. Each day, building condition decreases slightly. Each season, happiness shifts. Each tick, wages are paid before taxes are collected. Rules are deterministic — given the same state, they produce the same result. But they're also composable: the interaction between three simple rules can produce behaviour that wasn't written anywhere explicitly.

Events are the stochastic element that makes every run different. A fire breaks out. An investor arrives. A citizen gets promoted unexpectedly. Events prevent the simulation from settling into a predictable cycle.

Here's what that looks like in the simplest possible Python:

# State
city = {
    "treasury": 50000,
    "building_condition": 100,
    "day": 0
}

# Rules
def tick_day(city):
    city["day"] += 1
    # decay rate accelerates as condition falls — a neglected building deteriorates faster
    decay = 0.5 + (100 - city["building_condition"]) * 0.05
    city["building_condition"] -= decay
    if city["building_condition"] < 0:
        city["building_condition"] = 0
    # maintenance cost also rises as condition falls
    maintenance = (100 - city["building_condition"]) * 10
    city["treasury"] -= maintenance
    return city, maintenance, decay

# Run it — print every 5 days
print(f"{'Day':>4} | {'Condition':>9} | {'Decay':>6} | {'Daily Cost':>10} | {'Treasury':>12}")
print("-" * 58)
for i in range(60):
    city, cost, decay = tick_day(city)
    if (i + 1) % 5 == 0:
        print(f"{city['day']:>4} | {city['building_condition']:>9.1f} | {decay:>6.2f} | ${cost:>9.0f} | ${city['treasury']:>11,.0f}")

Enter fullscreen mode Exit fullscreen mode

Run that and watch what happens across 60 days. On day 5 the daily maintenance cost is $28. By day 30 it's $332. By day 50 the building hits zero condition and the city is losing $1,000 every single day — bleeding $5,000 from the treasury every five days with no end in sight.

You wrote two rules. Decay accelerates as condition falls. Cost rises as condition falls. Each rule makes the other worse. That compounding interaction — not written anywhere explicitly — is the feedback loop. The treasury isn't just draining. It's accelerating toward collapse. And the city hasn't even had a bad event yet.

That emergence is the point.


The Bugs Are Different

Here's what nobody tells you about simulation bugs: they don't crash.

A bug in a normal script announces itself. The program stops, Python prints a traceback, you fix it. A simulation bug produces the wrong numbers quietly. The city runs fine. Citizens appear to be doing things. But morale is trending wrong, or the treasury is draining faster than it should, or events aren't firing at the right frequency.

To find those bugs you can't just read a traceback. You have to reason about state. What values did this function receive? What should it have returned? What rule is interacting with what other rule to produce this drift?

That reasoning — sitting with a running system and building a mental map of its behaviour — is exactly the skill that professional debugging requires. Real codebases don't crash cleanly either. They produce wrong outputs, subtle regressions, behaviour that only appears under specific conditions. The muscle you build debugging a simulation is directly transferable.


Why a City Specifically

The inspiration for the book I eventually wrote was Championship Manager — a 1990s football management simulation. You don't play a character directly. You sit one level above the action, make decisions, and watch a simulation engine translate those decisions into results over time.

Those games weren't famous for their graphics. They were famous for making you care.

You approved a new residential block in year two because the treasury looked healthy. By year four the roads serving it are at 30% condition, commute times have doubled, and three citizens are considering leaving. You don't blame bad luck. You trace the decision back.

A city has everything a good teaching simulation needs:

  • Real state: population, infrastructure condition, economic health, political mood
  • Real rules: maintenance costs, population growth patterns, economic feedback loops
  • Real events: disasters, windfalls, elections, crises Nothing is metaphorical. It's a simplified model of actual dynamics. And every concept you encounter — object-oriented design, data structures, algorithms, testing — has an obvious real-world analogy in the city.

When you discover that a building is not just a name but a collection of named facts — condition, age, type, maintenance cost — dictionaries become natural, not abstract. When you need to track a citizen across many days, classes stop being a syntax exercise and become the obvious tool.


What Accumulation Teaches

The deepest thing a long-arc project teaches is something you can't get from isolated exercises: how systems age.

Code you write in chapter 4 is still running in chapter 14. Decisions you made early create constraints later. A function that seemed fine when it did one thing starts to resist change when you need it to do three things. You feel why small, focused functions matter — not because someone told you, but because yours got unwieldy and you had to fix it under pressure.

Consider this: in the book I wrote, there's a citizen named Tom. He's 63 when you first create him in chapter 4. By chapter 10 he retires. By chapter 12 his retirement is recorded in the City Chronicle — an append-only log of significant events. By chapter 14 a sparkline shows his morale trend across the years he worked.

Tom is not a real person. He's a named variable with richer state than most named variables. But when the simulation surfaces that another citizen, Elena, couldn't cover her rent last Tuesday, you notice in a way you wouldn't if it said "Citizen 4: rent shortfall." Names create the minimum viable fiction required for a simulation to generate the feeling of consequence.

And consequence is what makes the learning stick.


The Terminal as Canvas

One deliberate choice in the book: everything runs in the terminal. No web framework, no GUI library, no browser. Just Python and a terminal.

The terminal is universal — it runs identically on macOS, Linux, and Windows without installation beyond Python itself. But with the Rich library, it becomes genuinely expressive: colour, tables, panels, progress bars, live-updating layouts.

By chapter 8 of the book, the simulation runs inside a five-region live dashboard that updates in real time:

┌─────────────────────────────────────────────────────────────┐
│  NEW PYTHONVILLE   Day 847  |  Spring  Year 3               │
├──────────────┬──────────────┬──────────────┬────────────────┤
│  TREASURY    │  CITIZENS    │  BUILDINGS   │  EVENTS        │
│  $47,230     │  6 residents │  8 buildings │  Quiet day     │
│  ▼ trending  │  morale: 72  │  avg: 84%    │                │
├──────────────┴──────────────┴──────────────┴────────────────┤
│  CHRONICLE                                                   │
│  > Tom Wick retired after 847 days of service               │
│  > Elena Kosta promoted to Senior Engineer                  │
└─────────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

The terminal is also honest. There's nowhere to hide. If your dashboard renders wrong, you see it immediately. That short feedback loop between code and result is one of the most valuable things a learning environment can have.


How to Start Your Own

You don't need the book to start a simulation project. You need three things:

1. Pick a system you actually find interesting.
Cities work well. So do football leagues, ecosystems, stock markets, hospital wards, ant colonies. The subject doesn't matter. What matters is that it has things that change over time and decisions that have consequences.

2. Start with the absolute minimum viable state.
Don't design the whole thing upfront. Start with one entity, one rule, one event. Get it running. Then add one more thing. Let the architecture emerge from what the simulation needs rather than what you planned.

3. Name things.
Not entity_1 and entity_2. Names. The minimum viable fiction that makes you care about what happens. You'll debug harder, think more carefully, and learn more from a system whose inhabitants feel real.

The rest — data structures, algorithms, testing, optimisation — will arrive naturally when the simulation demands them. That's the whole point.


The Book

I spent two months building the structured version of this idea: Masters of the Metropolis, a simulation-first introduction to Python across 18 chapters. You build a city simulator from scratch — one layer at a time — until you have a live terminal dashboard, a seasonal economy, citizens with life arcs, save and load, elections, testing infrastructure, and a City Chronicle that makes every run unique.

If you've finished a Python basics course and don't know what to build next, this is that next step.

leanpub.com/metropolis — free sample available, no account needed.


What would you build a simulation of? Drop it in the comments — I'm genuinely curious what systems people find interesting.