Day 4 of 80

Loops & Iteration

Phase 1: Python Foundation

What You'll Build Today

Welcome to Day 4. Today is a turning point. Until now, your programs ran from top to bottom, executed each line once, and finished. That works for simple calculations, but it fails when you need to process data at scale.

Today, we are building a Text Analyzer. You will write a program that takes a block of raw text (like a paragraph from a document) and automatically extracts insights from it, such as counting specific characters or calculating density.

Here is what you will learn and why:

* For Loops: You need these to repeat an action for every item in a dataset (like processing every character in a tweet).

* The Range Function: You need this to run a process a specific number of times (like "try connecting 5 times").

* While Loops: You need these to keep a program running as long as a condition is true (like "keep waiting until the user says stop").

* Accumulator Pattern: You need this to keep a running total (like counting how many times the word "error" appears in a log).

* Break and Continue: You need these to have fine-grained control, like stopping a loop early if you find what you are looking for.

The Problem

Imagine you are working with a dataset of customer reviews. Your task is simple: print a log message for the first 5 reviews so you know the system is working.

With what you know so far, your code probably looks like this:

print("Processing Review #1...")

print("Processing Review #2...")

print("Processing Review #3...")

print("Processing Review #4...")

print("Processing Review #5...")

This is annoying, but manageable. But now, imagine your boss comes in and says, "Great, now do that for our database of 50,000 reviews."

To write that code manually, you would have to copy and paste that line 50,000 times. It would take days. If you made a typo in line 24,999, you might never find it. And if the number of reviews changes tomorrow? You have to rewrite the code.

This is the pain point of manual repetition. In the world of AI and data engineering, we never handle items one by one. We write logic that handles one item, and then we tell the computer: "Do this for everything."

There has to be a way to write the logic once and tell Python to repeat it.

Let's Build It

We are going to solve this using Loops. We will build up to our Text Analyzer step by step.

Step 1: The For Loop

The for loop is your primary tool for iteration. It tells Python: "For every individual item in this collection, do something."

Since we haven't learned Lists yet (that's tomorrow), we will loop over Strings. A string is just a collection of characters.

# A simple string

text = "GenAI"

# The For Loop

print("--- Starting Loop ---")

for letter in text:

print("Current letter is:")

print(letter)

print("--- End of Loop ---")

Why this matters:

Notice the indentation. Everything indented under for letter in text: happens 5 times (once for G, e, n, A, I). The variable letter is a placeholder. In the first loop, letter is "G". In the second, it is "e". You didn't have to write 5 print statements.

Step 2: The Range Function

Sometimes you don't have a string to loop over. You just want to repeat something a specific number of times (like the "Processing Review" problem above).

Python provides a function called range().

# Using range to repeat numbers 0 to 4
# Note: range(5) generates numbers 0, 1, 2, 3, 4 (it stops BEFORE the number you give it)

print("Starting batch job...")

for i in range(5):

# We usually use 'i' for 'index' or 'integer'

print(f"Processing Review #{i + 1}...")

print("Job complete.")

Why this matters:

You just solved the 50,000 review problem. If you change range(5) to range(50000), the computer does the work, and you still only wrote 3 lines of code.

Step 3: The Accumulator Pattern

Loops are rarely used just for printing. Usually, we want to calculate something as we loop. This is called the Accumulator Pattern.

We create a variable outside the loop (starting at zero), and update it inside the loop.

Let's count how many vowels are in a text string.

text = "Artificial Intelligence"

vowel_count = 0 # Initialize the accumulator

print(f"Analyzing: {text}")

for char in text:

# Check if the current character is a vowel # We convert to lower case so 'A' and 'a' both count

if char.lower() == 'a' or char.lower() == 'e' or char.lower() == 'i' or char.lower() == 'o' or char.lower() == 'u':

vowel_count = vowel_count + 1

print(f"Found a vowel: {char}")

print("----------------")

print(f"Total vowels found: {vowel_count}")

Why this matters:

This is the foundation of data analysis. Whether you are summing sales figures or counting tokens for an LLM prompt, you are using the accumulator pattern.

Step 4: The While Loop

A for loop runs for a set amount of times. But what if you don't know how many times you need to loop? What if you want to loop until something happens?

That is a while loop.

fuel_level = 5

print("Starting engine sequence...")

while fuel_level > 0:

print(f"Engine running... Fuel: {fuel_level}")

fuel_level = fuel_level - 1 # Decrease fuel

print("Engine stopped. Out of fuel.")

Common Mistake: If you forget to decrease fuel_level, the condition fuel_level > 0 will always be true. This creates an Infinite Loop, and your program will run forever (or until your computer crashes).

Step 5: Break and Continue

Sometimes you need to interrupt the loop.

* break: Stop the loop completely right now.

* continue: Skip the rest of this specific iteration and go to the next one.

Let's look for a specific letter, but skip spaces.

phrase = "Data Science"

target = "S"

print(f"Scanning '{phrase}' for '{target}'...")

for char in phrase:

if char == " ":

print("(Skipping space)")

continue # Jump back to the start of the loop for the next character

print(f"Checking: {char}")

if char == target:

print("TARGET FOUND! Stopping search.")

break # Kill the loop entirely

print("Scan finished.")

Step 6: The Main Project - Text Analyzer

Now we will put it all together. We will build a tool that analyzes a user's text input. Since we don't know Lists yet, we can't easily break the text into individual words, but we can perform deep analysis on the characters.

We will calculate:

  • Total characters (excluding spaces).
  • The count of a specific letter the user is interested in.
  • The percentage of the text that is made up of that letter.
  • print("=== TEXT ANALYZER TOOL ===")
    
    # 1. Get Inputs
    

    text = input("Enter a sentence to analyze: ")

    target_letter = input("Which letter do you want to count? ")

    # 2. Initialize Accumulators

    total_chars_no_spaces = 0

    target_count = 0

    # 3. The Loop

    print(f"\nAnalyzing '{text}'...")

    for char in text:

    # Logic 1: Count valid characters (skip spaces)

    if char == " ":

    continue # Skip the math for spaces

    total_chars_no_spaces += 1 # Add 1 to total

    # Logic 2: Check for target match # We force both to lowercase to ensure 'A' matches 'a'

    if char.lower() == target_letter.lower():

    target_count += 1

    # 4. Final Calculations # Prevent division by zero error if they just typed spaces

    if total_chars_no_spaces > 0:

    percentage = (target_count / total_chars_no_spaces) * 100

    else:

    percentage = 0

    # 5. Output Results

    print("\n=== RESULTS ===")

    print(f"Total non-space characters: {total_chars_no_spaces}")

    print(f"Occurrences of '{target_letter}': {target_count}")

    print(f"Frequency: {percentage}%")

    Run this code with the input "Hello World" and search for "l". You should see it count the characters, find the Ls, and give you a percentage.

    Now You Try

    Here are three extensions to the Text Analyzer. Try to implement them one by one.

    1. The Number Hunter

    Modify the loop to count how many numeric digits (0-9) are in the text.

    Hint:* You can check if a character is a number using char.isdigit() which returns True or False. 2. The Reverse Printer

    Create a new loop that prints the string backward.

    Hint:* You can't easily loop backward with a simple for char in text, but you can use range(). Hint:* len(text) gives you the length. text[i] gives you the character at index i. Try looping through the range of indexes in reverse. 3. The "Stop at X" Feature

    Modify the Main Project so that if the loop encounters the character "X" (capital X), it immediately stops analyzing and prints "Emergency Stop triggered."

    Hint:* Use the break keyword inside an if statement.

    Challenge Project: API Retry Simulator

    In real-world AI engineering, API calls (like sending a prompt to ChatGPT) often fail due to network issues. You cannot just give up; you have to try again.

    Your challenge is to write a script that attempts to "connect" to a server.

    Requirements:
  • Use a while loop to manage the attempts.
  • Allow a maximum of 3 attempts.
  • Use the import random library to simulate success or failure. success = random.choice([True, False]) will randomly pick True or False.
  • If the connection fails, print "Connection failed. Retrying..." and increase the attempt counter.
  • If the connection succeeds, print "Connected!" and break the loop.
  • If the loop finishes 3 attempts without success, print "Max retries reached. Exiting."
  • Example Output (Scenario: Failure):
    Attempt 1: Connecting...
    

    Connection failed. Retrying...

    Attempt 2: Connecting...

    Connection failed. Retrying...

    Attempt 3: Connecting...

    Connection failed. Retrying...

    Max retries reached. Exiting.

    Example Output (Scenario: Success):
    Attempt 1: Connecting...
    

    Connection failed. Retrying...

    Attempt 2: Connecting...

    Connected!

    Hints:

    * You need a variable like attempts = 0 before the loop.

    * Your while condition needs to check if attempts < 3.

    * Don't forget to import random at the very top of your file (import random).

    What You Learned

    Today you moved from writing static scripts to writing automated engines.

    * For Loops: You learned to process data sequences one item at a time.

    * Range: You learned to generate number sequences for iteration.

    * While Loops: You learned to create logic that runs until a condition changes.

    * Accumulators: You learned to count and sum data inside a loop.

    Why This Matters:

    Large Language Models (LLMs) like GPT-4 generate text using a loop. They generate one token (word part), look at it, then generate the next one, looping thousands of times until they hit a "stop" token (a break command). You have just learned the fundamental logic of text generation.

    Tomorrow:

    You might have noticed it was annoying to analyze text character by character. Wouldn't it be better to analyze it word by word? To do that, we need a way to store groups of items together.

    Tomorrow: Lists - storing multiple items together.