Python Loops & Code Tracing

Learn to "read" code like a detective - essential skill for all programmers!

What You'll Learn
  • Understand Python for and while loops (step by step)
  • Trace code execution to find hidden bugs
  • See why automated tools can't replace human thinking
  • Practice with simple, real-world examples
Why Manual Tracing Still Matters

Why Loops Matter

Loops handle repetitive tasks - like processing lists of data, counting items, or repeating actions until a condition is met.

Tracing loops helps you understand exactly how data changes with each repetition.

Automated Tools vs. Human Thinking

Tool Limitation Why You Need Tracing
Debugger Doesn't know where to look You need to understand the flow
Unit Tests Miss logic errors in edge cases Tests don't explain WHY things are wrong
Static Analyzer Can't understand business logic Only you know what code should really do
Python For Loops

What is a "sequence"?

A sequence is just a list of things:

  • Your shopping list: 🍎 Apple, 🍌 Banana, 🍒 Cherry
  • Names in your phone contacts
  • Numbers from 1 to 10

A for loop goes through each item in your list, one by one.

# Simple for loop example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Try It Live!

Enter items (comma separated):

Starting for loop...
Print: "apple"
Print: "banana"
Print: "cherry"
Print: "date"
Print: "egg"
Loop finished! Processed 5 items.

Real Example: Counting Website Visitors

# Count visitors each hour
hourly_visitors = [45, 12, 78, 23, 56, 89, 34]
total_visitors = 0

for visitors in hourly_visitors:
    total_visitors += visitors
    print("Print:", visitors, "visitors → Total:", total_visitors)
Counting website visitors by hour...
Print 1: 45 visitors → Total: 45
Print 2: 12 visitors → Total: 57
Print 3: 78 visitors → Total: 135
Print 4: 23 visitors → Total: 158
Print 5: 56 visitors → Total: 214
Print 6: 89 visitors → Total: 303
Print 7: 34 visitors → Total: 337
Total visitors today: 337
Python While Loops

While = "Keep doing this as long as..."

Examples:

  • Keep cooking while the timer is running ⏱️
  • Keep driving while you have gas ⛽
  • Keep counting while number is less than 10 🔢
# Simple while loop example
counter = 1
while counter <= 5:
    print("Counting:", counter)
    counter += 1

Try a While Loop

Counting will happen step by step...
Tracing Code - Step by Step

What is Tracing?

Tracing is like reading a recipe while cooking:

  1. Read the first instruction
  2. Do it
  3. Check what changed
  4. Write it down
  5. Repeat for next instruction

Real Bug Hunt: Finding the Smallest Number

The Task: Find the smallest number in a list

Given: [24, 16, 35, 42, 7] → Should find: 7

items = [24, 16, 35, 42, 7]
lowest = items[0]

for current in range(1, len(items)):
    if lowest < items[current]:
        lowest = items[current]

print("Lowest number:", lowest)

Let's Trace Through to Find the Bug

Step lowest Condition [0] [1] [2] [3] [4]
1 24 24 16 35 42 7

Find and Fix the Bug

The code doesn't find the correct smallest number. Can you figure out why?

Look at the trace table above. What should the comparison operator be?

AI Learning & Tracing

How AI Learns from Mistakes

Even AI systems need debugging! When an AI makes wrong predictions, we need to trace through its "thinking" to find why.

The Cat/Dog Classifier Problem

Imagine an AI that should tell cats from dogs, but it keeps saying cats with collars are dogs.

Why? Let's trace through what it learned:

# Simplified AI thinking process
def check_animal(features):
    # features: [pointy_ears, fluffy_tail, has_collar]
    # weights: how important each feature is
    weights_for_cat = [0.8, 0.6, -0.2]
    weights_for_dog = [0.3, 0.7, 0.9]
    
    cat_score = 0
    dog_score = 0
    
    for i in range(len(features)):
        cat_score += features[i] * weights_for_cat[i]
        dog_score += features[i] * weights_for_dog[i]
    
    if cat_score > dog_score:
        return "Cat"
    else:
        return "Dog"

Test the AI Classifier

Enter features (1 = yes, 0 = no):

Tracing the AI Classification

Step Feature Value Cat Weight Dog Weight Cat Contribution Dog Contribution Cat Score Dog Score
What You've Learned
  • For loops go through lists item by item
  • While loops keep going while condition is true
  • Tracing means following code step by step like a detective
  • Bugs hide in logic - automated tools can't always find them
  • You're the detective - tracing helps you understand WHY code works (or doesn't)