Repeating Actions with Loops

The Power of Loops

Why use loops?

In programming, we often need to perform the same task multiple times—like sending an email to every customer in a list or checking a temperature sensor every minute. Instead of writing the same code over and over, we use loops.

Welcome! In programming, we often need to perform the same task multiple times. Imagine writing code to send a thousand emails one by one. It's exhausting! Loops allow us to write a block of code once and tell Python to repeat it as many times as needed.

Iterating with 'for' Loops

The 'for' Loop

A for loop is used when you want to iterate over a sequence (like a list of names or a range of numbers). You use it when you know in advance how many times you need to repeat the action.

The 'for' loop is your go-to tool for sequences. Notice the structure: we define a variable, like 'item', to represent the current object in the sequence. We also use the range function to generate numbers. Remember, range(5) starts at zero and stops at four!

Interactive 'for' Loop

Click the Next button to see how the loop moves through the list of astronauts.

Let's see a 'for' loop in action. Here is a list of astronauts. Click 'Next' to watch the 'name' variable change as we move through the list. Now the variable 'name' holds the next value. The print function executes using this specific name.

Conditional Logic with 'while'

The 'while' Loop

A while loop repeats as long as a certain condition is true. It is ideal for situations where you don't know exactly how many repetitions you'll need.

What if you don't know the exact number of repeats? The 'while' loop runs as long as a condition stays True. But be careful! If the condition never becomes False, you'll create an infinite loop that can crash your program.

Mission Control: The Countdown

Build a countdown timer. You must update the variable to prevent an infinite loop!

It's time for a rocket launch. We have a variable 'count' set to 3. If we don't decrease it inside the loop, the rocket will never launch! Click the line of code that will fix our loop. Perfect! By subtracting 1 each time, the count eventually hits zero, the loop stops, and we have liftoff!

The Golden Rule: Indentation

How to Apply Loops

  1. Identify the goal: Process a list (for) or wait for a change (while).
  2. Header: End the line with a colon (:).
  3. Indentation: The body must be indented by 4 spaces.

In Python, whitespace matters. After the colon, every line you want to repeat must be indented. If it's not indented, Python thinks the loop has ended. Think of indentation as a container for your repeated actions.

Debugging the Loop

A fellow programmer wrote this loop, but it's not working as expected. Diagnose the error.

count = 5
while count > 0:
    print("Counting down...")
print("Blast off!")

Take a look at this code. It's supposed to count down and then print 'Blast off', but it's stuck. Why is this an infinite loop? Type your diagnosis and suggest a fix.

Summary & Best Practices

Loop Mastery

Great job! You've mastered the basics of Python loops. Remember: use 'for' for lists and ranges, and 'while' for conditions. Always double-check your indentation and your loop exit strategy. You're ready to start building more complex programs!