12 Loops
12.1 The Wall
AI’s loop ran forever. Or it skipped items. Or it processed the last item twice. You stared at the code, for i in range(len(data)):, and could not tell whether the range was right. You asked AI to fix the infinite loop and it restructured the entire program instead of fixing the one condition.
Loops are where AI makes off-by-one errors, forgets break conditions, and creates unnecessarily complex iterations. If you cannot trace through a loop manually, you will never spot these bugs.
This chapter fixes that.
12.2 Thinking Session
12.2.1 Getting Oriented
What are the two types of loops in Python, for and while? When should I use each one? And why does AI-generated code sometimes use for i in range(len(items)): instead of just for item in items:? Is the longer version ever better?
Your AI should explain: for iterates over a sequence (use when you know what you are iterating over), while repeats until a condition is false (use when you do not know how many times). The range(len()) pattern gives you the index, sometimes needed, but enumerate() is better for that.
12.2.2 Go Deeper
Explain break, continue, and else on loops in Python. I see AI using all three and I do not understand the else on a for loop. That seems strange. When would you actually use it?
break exits the loop immediately. continue skips to the next iteration. The else on a loop runs only if the loop completed without break. It is useful for “search” patterns where you want to know if you found something. If your AI cannot explain a practical use case for loop else, the concept is probably not important enough to use.
What are common loop patterns in Python? I see AI using counting loops, accumulator loops, search loops, and filter loops. Show me one example of each and tell me when to recognise each pattern.
12.2.3 Challenge It
What is wrong with each of these loops?
# Loop 1
while True:
data = input("Enter data: ")
process(data)
# Loop 2
items = [1, 2, 3, 4, 5]
for i in range(len(items)):
if items[i] % 2 == 0:
items.remove(items[i])
# Loop 3
total = 0
for i in range(10):
total = iLoop 1: no break. It runs forever. Loop 2: modifying a list while iterating over it skips items (removing index 1 shifts everything, so index 2 becomes the old index 3). Loop 3: total = i overwrites instead of accumulating, should be total += i. These are all bugs AI generates regularly.
12.2.4 What You Should Have Learned
foriterates over sequences,whilerepeats on a conditionbreakexits,continueskips,elseruns if no break- Do not modify a list while iterating over it
- Use
enumerate()instead ofrange(len()) - Common patterns: counting, accumulating, searching, filtering
while Trueneeds abreakcondition
12.3 The Gap
You can now trace through any loop AI generates and predict its behaviour. You know the difference between accumulating (+=) and overwriting (=). You know why modifying a list during iteration is dangerous. When AI gives you a loop, you can verify it will terminate and process every item exactly once.
In the Building Session, you will add word processing to your chatbot, iterating through user input to extract meaning.
12.4 Building Session
12.4.1 The Spec
Add loop-based text processing to your chatbot:
- Count specific keywords using a for loop
- Process each word in the user’s message
- Use a while loop for multi-step interactions (e.g., a quiz)
- Add a “quiz” command that asks 3 Python questions in sequence
12.4.2 Prompt It
Update my chatbot to v1.2. Add loop-based features:
- In get_response(), use a for loop to count how many “positive” words (good, great, nice, thanks, awesome) appear in the input
- If 2+ positive words found, respond with extra enthusiasm
- Add a “quiz” command that uses a while loop to ask 3 Python trivia questions, tracks the score, and shows results at the end
- The quiz should use a list of (question, answer) tuples
Keep existing features.
12.4.3 Read the Code
Your AI will produce something like this:
POSITIVE_WORDS = ["good", "great", "nice", "thanks", "awesome"]
QUIZ_QUESTIONS = [
("What function prints output?", "print"),
("What type is 3.14?", "float"),
("What keyword exits a loop?", "break"),
]
def count_positive(text):
"""Count positive words in text."""
words = text.lower().split()
count = 0
for word in words:
if word in POSITIVE_WORDS:
count += 1
return count
def run_quiz(bot_name):
"""Run a Python trivia quiz."""
score = 0
question_num = 0
while question_num < len(QUIZ_QUESTIONS):
question, answer = QUIZ_QUESTIONS[question_num]
user_answer = input(f"Q{question_num + 1}: {question} ").strip().lower()
if user_answer == answer:
print(f"{bot_name}: Correct!")
score += 1
else:
print(f"{bot_name}: The answer was '{answer}'.")
question_num += 1
print(f"{bot_name}: Quiz done! Score: {score}/{len(QUIZ_QUESTIONS)}")count_positive() uses a for loop with an accumulator pattern (count += 1). run_quiz() uses a while loop because the number of iterations depends on the question list length. The tuple unpacking question, answer = QUIZ_QUESTIONS[question_num] is a pattern AI uses frequently.
12.4.4 Stretch It
Rewrite count_positive() as a list comprehension that filters positive words, then use len() on the result. Compare both versions, which is more readable?
12.5 Your Chatbot So Far
- Ch 1-10: Full feature set with functions and categorised responses
- Ch 11: Conversation history, random responses
- Ch 12: Word counting loop, quiz with while loop
12.6 Quick Reference
# for loop
for item in items:
print(item)
for i, item in enumerate(items):
print(f"{i}: {item}")
# while loop
while condition:
# do something
if done:
break
# Loop control
break # exit loop
continue # skip to next iteration
# Patterns
# Accumulate
total = 0
for x in numbers:
total += x
# Filter
evens = [x for x in numbers if x % 2 == 0]
# Search
for item in items:
if item == target:
print("Found!")
break