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

推荐订阅源

H
Help Net Security
T
ThreatConnect
SecWiki News
SecWiki News
F
Future of Privacy Forum
AWS News Blog
AWS News Blog
C
Cisco Blogs
A
Arctic Wolf
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
V2EX
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
K
Kaspersky official blog
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Privacy International News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News | PayPal Newsroom
Schneier on Security
Schneier on Security
NISL@THU
NISL@THU
Microsoft Azure Blog
Microsoft Azure Blog
量子位
The Hacker News
The Hacker News
Stack Overflow Blog
Stack Overflow Blog
Security Latest
Security Latest
M
Microsoft Research Blog - Microsoft Research
Google Online Security Blog
Google Online Security Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
InfoQ
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
The Cloudflare Blog
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Troy Hunt's Blog
F
Fox-IT International blog
S
Security @ Cisco Blogs
博客园 - 司徒正美
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Comments on: Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LINUX DO - 最新话题
GbyAI
GbyAI
Project Zero
Project Zero
腾讯CDC
T
Tailwind CSS Blog

DEV Community

LangGraph 워크플로우 템플릿 (v39) The git Commands You Forgot Exist (And Why AI Workflows Make Them Relevant Again) Six Levels of MCP Servers One container to replace Grafana + Loki + Tempo + Prometheus The Request/Response Cycle, HTTP, Auth, JWT, OAuth & Sessions — Explained Properly Creating a Custom Grid Editor tool in Unreal Engine 我做了个付费 Telegram bot。Telegram Stars 实际给开发者多少钱,我算了一笔账。 I Got 96% Recall on LLM Hallucination Detection With No ML Model – Just 50 Lines of Python A practitioner's guide to getting more value out of AI coding: agent quality & token optimization How to Handle Telegram Albums in Telegraf I Built a Multilingual Spam Detection Dataset with 149K+ Messages Across 23 Languages How to Handle Telegram Albums in grammY RAG 시스템 실전 구축 (v38) Beyond Pip Install: Why Your AI Agent Needs a "Hermetic" Life-Support System to Survive Resume Building using HTML & CSS SpecFlow: Multi-Agent SDD in Cursor (4 phases, /approve, single code writer) Running ASR for smart homes in the NPU of Intel processors "Building a CI/CD Pipeline From Scratch: A Practical Guide for Developers (with GitHub Actions)" SpecFlow: SDD multi-agente en Cursor (4 fases, /approve, un solo escritor de código) How to Extract Your Full Team Hierarchy from HubSpot (the API doesn't expose it) Adobe Commerce Cloud now costs $40k/year. We migrated from Adobe Commerce to Magento Open Source — here's the honest breakdown .klickd v4.0.0 — Portable AI memory with constraints, strict schemas, and test vectors We Trust Third Party Code, It’s Time to Trust AI Generated Code LangGraph 워크플로우 템플릿 (v38) Sustainable AI Starts with Efficient AI Find Remove duplicated files in Google Drive How to Detect GPU Waste in a Kubernetes Cluster The Privacy Bug in My First Chrome Extension (And How to Avoid It) Serverless Mental Models: What They Don't Tell You Before You Build Preventing GPT hallucination in automated content pipelines: how I structure Make.com flows with data injection Hmm, where were we? AI Visibility Tools, Math Proofs, and Stripped Guardrails Shape Developer Landscape How AI and Electronics Are Changing Healthcare Devices: The Future of Smart Healthcare Author: Shivam Wakade | Founder, PrivSR Making Claude Sound Like Optimus Prime Understanding Reinforcement Learning with Human Feedback Part 5: Training the Reward Model with Loss Functions Learning Progress Pt.20 How Secure LoRa Communication Devices Work: Building the Future of Private and Long-Range Connectivity Author: Shivam Wakade | Founder, PrivSR How I Rebuilt an RPG Map Editor with Rust, React, and WASM Building a System That Automates YouTube Post-Production Building a 100% Serverless Digital Asset Packager in the Browser Game Recommended AI What is Human-In-The-Loop (HITL)? Deep Dive: React Server Components in TanStack Start Migrating off Google Analytics: Umami vs Plausible vs Fathom Building a Portfolio That Actually Demonstrates Software Engineering Async/Await in JavaScript: From Callbacks to Clean Code (2026) Benchmarking LLM Structured Outputs Angular 21 Multiselect Dropdown: A Migration-Friendly Component with Live Functional Tests ShareBox v5 — GPU transcoding, Netflix-style grid, and why I don't need Plex anymore TOML Schema is live Handling Duplicate Shopify Webhook Events (And Why You Must) Original Kubernetes Dashboard — retired upstream, upgraded to Angular 21. لماذا أسست ترينافو للتجار العرب الذين تتجاهلهم المنصات الغربية Construyendo un recomendador de películas en Python: de los datos al modelo When APIs Lie: A Lesson in Defensive Debugging Pope Leo XIV's AI Encyclical: What Builders Must Know (2026) Donna v0.3.0 HTB — MonitorsFour | Writeup The Free Tool You Trust Is the One You Should Fear the Most HTB — MonitorsFour | Writeup Fr 97. Embeddings and Vector Search: Semantic Search That Works Deep Dive: Building "Gravity Paint" - A Tactile Physics Instrument with React, Matter.js, and p5.js ABAP Unit Testing with Test Doubles and Mocking Frameworks: A Senior Architects Guide to Isolating Dependencies in SAP S/4HANA LeetCode Solution: 5. Longest Palindromic Substring kovax-react 0.8: Tailwind v4 preset, FormField adapters, ColorModeScript, and Storybook I built an AI résumé tool that refuses to lie about your experience The hat Azure Entra ID User & Role Management — Step-by-Step Practical Guide With A Simple Excercise The AI-Native Company: How a Single Founder Can Build Global Organizations Powered by AWS and an Ecosystem of Artificial Intelligences Building a Lightweight Remote MCP Knowledge Base on Cloudflare Workers Why I built Trinavo for the MENA merchants Western platforms ignore The N+1 Query That Killed Our Database, And How I Fixed It Docstrings vs Markdown Docs: What Should Developers Actually Write? Training Data Provenance: The Manifest Diff That Explains the Hash Add SVGIcons MCP to Claude Code and Find SVG Icons from Your Terminal 3 CLI Tools You Can Buy with Crypto — No KYC, No Subscriptions COSS Weekly: OpenClaw competitor NanoClaw Raises $12M, Dust Raises $40M, Sonar Acquires Gitar, and more How to know if you actually need mobile proxies (without buying any) Building Cursor for Community: A Buildathon Built on Time Pressure How we built a PII masking layer for LLM APIs — local detection, reversible tokens, one line to integrate Why MLFQ Was Way Ahead of Its Time Add Runtime Limits to Claude Agent Workflows I Built a Prompt Injection Detector with 98% Recall on Unseen Attacks. Here's Why Data Beat Architecture. 8 Vite Config Options Every Developer Should Know (Vite 8) Feature Flags That Forgot to Leave Why Trust Infrastructure Is Becoming the Hidden Layer of Donation Platforms XyPriss: Rethinking Core Performance and Zero-Trust Architecture in Modern Backends Designing Configuration for Scalable Treasure Hunts SSH Login Delays: The 10-Second Wait That Drives Us Crazy Building Production Multi-Agent Workflows in n8n: What 50 Deployments Taught Us A 3-layer memory system that gives Claude Code persistent context across sessions. Trishul SNMP Suite 2.0.1: Better MIBs, Traps, and SNMP Labs How I built a production AI SaaS as a solo developer Auto-labelling 1.2M robotics frames with VLMs: a failover story India’s Laws Were Not Built for AI — And Courts Are Filling the Gap skill-insp: A Skill That Scores Other Skills Clprolf Minimalist Messaging in the Age of AI What's actually in a good .cursorrules file? I built 10 of them — here's what I learned Building Strong Python Basics – Loops, Functions and Logic
Python Week 3: We Stopped Repeating Ourselves (Loops!)
Navas Herber · 2026-05-26 · via DEV Community

I started this session with a challenge.

"Jose," I said, "print the names of all 40 students in this dataset - one per line."

He looked at me. Then at his keyboard. Then started typing print("Amina").

I let him get to the third name before I stopped him.

"What if there were 10,000 students?"

Silence.

"What if the list changed every week?"

More silence.

That's the setup for loops. You don't teach loops by explaining them - you first make people feel the pain of not having them. Then the solution lands differently.


The for Loop: Working Through a List

The for loop is Python's way of saying: go through every item in this collection and do something with each one.

My analogy: a class register. The teacher calls each name in order, marks attendance, moves to the next. They don't skip anyone. They don't stop early. They go through the whole list.

students = ["Amina", "Brian", "Njeri", "Kamau", "Wanjiku"]

for student in students:
    print(f"Good morning, {student}! 👋")

Enter fullscreen mode Exit fullscreen mode

Good morning, Amina! 👋
Good morning, Brian! 👋
Good morning, Njeri! 👋
Good morning, Kamau! 👋
Good morning, Wanjiku! 👋

Enter fullscreen mode Exit fullscreen mode

Five names. One loop. If the list had 10,000 names, same code - still works.

Jose closed his half-written print() statements and deleted them. That reaction is why I love teaching this session.


range(): Counting Without a List

Sometimes you don't have a list of items - you just want to repeat something a specific number of times. That's what range() is for.

for i in range(5):
    print(f"Attempt {i + 1}")

Enter fullscreen mode Exit fullscreen mode

Attempt 1
Attempt 2
Attempt 3
Attempt 4
Attempt 5

Enter fullscreen mode Exit fullscreen mode

Then came the question I wait for every cohort.

"Why does range(5) go from 0 to 4? Why not 1 to 5?"

Because Python counts like a programmer - starting from zero. range(5) means "give me 5 numbers starting at 0" - so 0, 1, 2, 3, 4.

If you want 1 to 5, you tell it explicitly:

for i in range(1, 6):
    print(i)

Enter fullscreen mode Exit fullscreen mode

1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

You can even count in steps:

# Count in 10s - like a matatu filling up every 10km
for km in range(0, 51, 10):
    print(f"Distance covered: {km} km")

Enter fullscreen mode Exit fullscreen mode

Distance covered: 0 km
Distance covered: 10 km
Distance covered: 20 km
Distance covered: 30 km
Distance covered: 40 km
Distance covered: 50 km

Enter fullscreen mode Exit fullscreen mode


Doing Real Work Inside a Loop

A loop is only useful if you do something meaningful inside it. We levelled up from printing names to processing data:

scores = [78, 45, 92, 61, 55, 88, 34, 73]
total = 0

for score in scores:
    total = total + score

average = total / len(scores)
print(f"Class average: {average:.1f}")

Enter fullscreen mode Exit fullscreen mode

Class average: 65.8

Enter fullscreen mode Exit fullscreen mode

Then we added a conditional inside the loop - finding students who failed:

scores = [78, 45, 92, 61, 55, 88, 34, 73]

print("Students who need support:")
for i in range(len(scores)):
    if scores[i] < 50:
        print(f"  Student {i + 1}: scored {scores[i]} - below pass mark")

Enter fullscreen mode Exit fullscreen mode

Students who need support:
  Student 2: scored 45 - below pass mark
  Student 7: scored 34 - below pass mark

Enter fullscreen mode Exit fullscreen mode

This is where students started to see it. A loop plus a conditional is already a mini data pipeline. You're iterating through records, applying a rule, flagging what matters.


The while Loop: Keep Going Until Something Changes

The for loop goes through a fixed collection. The while loop is different - it keeps running as long as a condition is true, and you don't always know in advance how many times that will be.

My analogy: a matatu waiting at the stage. It doesn't leave after a fixed number of passengers - it waits until it's full. While there's space, keep accepting passengers.

passengers = 0
capacity = 14

while passengers < capacity:
    passengers += 1
    print(f"Passenger {passengers} boards. Seats remaining: {capacity - passengers}")

print("Matatu is full. Twende!")

Enter fullscreen mode Exit fullscreen mode

Passenger 1 boards. Seats remaining: 13
Passenger 2 boards. Seats remaining: 12
...
Passenger 14 boards. Seats remaining: 0
Matatu is full. Twende! 

Enter fullscreen mode Exit fullscreen mode

A more practical use - a simple login system that keeps asking until you get it right:

password = "lux2024"
attempts = 0

while True:
    entry = input("Enter password: ")
    attempts += 1

    if entry == password:
        print(f"✅ Access granted after {attempts} attempt(s).")
        break
    else:
        print("❌ Wrong password. Try again.")

Enter fullscreen mode Exit fullscreen mode

Enter password: wrongpass
❌ Wrong password. Try again.
Enter password: lux2024
✅ Access granted after 2 attempt(s).

Enter fullscreen mode Exit fullscreen mode


The Infinite Loop Nobody Saw Coming

This was the moment of the session.

One student - Aisha - was building the login checker and forgot the break. Her loop just kept asking for the password. Forever. Her laptop stopped responding to anything else.

"How do I stop it?!"

Ctrl + C. Always Ctrl + C.

She pressed it. The program stopped. The room exhaled.

I told everyone to write Ctrl + C at the top of their notes and circle it. It's the emergency exit for every infinite loop - and you will need it at some point. Better to learn it when Aisha accidentally teaches you than when you're alone at midnight wondering why your computer is hot.

The lesson from Aisha's loop: every while True must have a break inside it. Without a way out, the loop runs until you force-quit the program or your laptop gives up.


break and continue: Taking Control of the Loop

Once students understood that loops run to completion, I showed them two ways to interrupt that:

break - stop the loop entirely and exit:

# Search for a student in the register
register = ["Amina", "Brian", "Njeri", "Kamau", "Wanjiku"]
target = "Njeri"

for student in register:
    if student == target:
        print(f"Found {target}! ✅")
        break   # No need to keep searching
    print(f"Checking {student}...")

Enter fullscreen mode Exit fullscreen mode

Checking Amina...
Checking Brian...
Found Njeri! ✅

Enter fullscreen mode Exit fullscreen mode

continue - skip this item and move to the next one:

# Print all scores, but skip anyone who was absent (score = 0)
scores = [78, 0, 92, 0, 55, 88]

for score in scores:
    if score == 0:
        continue   # Skip absent students
    print(f"Score: {score}")

Enter fullscreen mode Exit fullscreen mode

Score: 78
Score: 92
Score: 55
Score: 88

Enter fullscreen mode Exit fullscreen mode

The analogy that landed for continue: a teacher calling the register and the student is absent. You don't stop the whole class - you just say "absent" and move to the next name.


Nested Loops: A Loop Inside a Loop

I saved this for the end - the concept that always gets a dramatic reaction.

# Multiplication table (3x3 preview)
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")
    print("---")

Enter fullscreen mode Exit fullscreen mode

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---

Enter fullscreen mode Exit fullscreen mode

"The outer loop runs - and every time it does, the inner loop runs all the way through."

You could see people mentally tracing the logic. I gave them a minute to sit with it before moving on. Some concepts need a moment, not a faster explanation.

A practical example - checking every student against every subject:

students = ["Amina", "Brian", "Njeri"]
subjects = ["Maths", "English", "Science"]

for student in students:
    for subject in subjects:
        print(f"{student}{subject}")
    print()

Enter fullscreen mode Exit fullscreen mode

Amina → Maths
Amina → English
Amina → Science

Brian → Maths
Brian → English
Brian → Science

Njeri → Maths
Njeri → English
Njeri → Science

Enter fullscreen mode Exit fullscreen mode


Practice Problems

Easy:

# 1. Print numbers 1 to 20 using a for loop and range()
# 2. Print only even numbers between 1 and 30
# 3. Loop through this list and print each item in uppercase:
#    groceries = ["unga", "sukari", "mafuta", "chumvi"]

Enter fullscreen mode Exit fullscreen mode

Medium:

# A simple ATM PIN checker - give the user 3 attempts
correct_pin = "4821"
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    pin = input("Enter your PIN: ")
    attempts += 1

    if pin == correct_pin:
        print("PIN accepted. Welcome.")
        break
    else:
        remaining = max_attempts - attempts
        if remaining > 0:
            print(f"Wrong PIN. {remaining} attempt(s) left.")
        else:
            print("Account locked. Please visit your branch.")

Enter fullscreen mode Exit fullscreen mode

Challenge:

# Sales summary - loop through a list of daily sales,
# calculate total, find the highest day, count days below target

daily_sales = [12400, 8750, 15200, 6300, 19800, 11050, 9400]
target = 10000

# Your code here:
# 1. Total sales for the week
# 2. Best day (highest sales)
# 3. How many days missed the target

Enter fullscreen mode Exit fullscreen mode


What I Noticed Teaching This Session

1. The pain-first setup works every time. Making Jose start writing 40 print() statements - even for just 3 names - made the loop feel like a rescue, not a concept.

2. Aisha's infinite loop was the best teaching moment of the week. An accident in front of the class, handled calmly, teaches Ctrl + C and loop safety more effectively than any slide ever could. I didn't plan it. I didn't need to.

3. Students started thinking like data people. When we looped through scores and flagged students below 50, someone said: "This is basically filtering - like SQL WHERE." That connection was electric. That's exactly what it is.

4. break and continue need contrast to make sense. Showing them without break (loop continues past the found item) before showing with break made the difference immediately visible.


What's Coming in Week 4: Functions

Right now our programs do things — but they can't remember how to do them. If we need to calculate a grade three times in different places, we write the logic three times. That's wrong.

Functions fix this:

def calculate_grade(score):
    if score >= 80:
        return "A"
    elif score >= 70:
        return "B"
    elif score >= 60:
        return "C"
    elif score >= 50:
        return "D"
    else:
        return "F"

print(calculate_grade(85))   # A
print(calculate_grade(62))   # C
print(calculate_grade(41))   # F

Enter fullscreen mode Exit fullscreen mode

Write it once. Use it anywhere. That's next week.


Try It Yourself

Start with the ATM PIN checker - it combines everything from Week 2 (conditionals) and Week 3 (while loops). If that runs cleanly, you're ready for functions.


I'm a data trainer in Nairobi running a full data programme -
Python foundations → Data Science or Data Engineering specialisations.
I write weekly about what we covered, what worked, and what surprised me.
Follow along or drop your questions in the comments.