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.
- Loops automate repetitive tasks.
- They prevent code duplication.
- Python uses 'for' and 'while' loops.
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.
- Syntax:
for item in sequence: - range(): Generates numbers, e.g.,
range(5)gives 0 to 4.
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!
- Iterates over sequences like lists or ranges.
- Ideal when the number of repetitions is known.
- Uses the 'range()' function for numeric sequences.
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.
- The loop variable updates each iteration.
- The code inside the loop executes once for every item.
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.
- Syntax:
while condition: - Caution: Watch out for infinite loops!
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.
- Repeats based on a True/False condition.
- Used when the end point depends on external factors.
- Requires a way to eventually make the condition False.
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!
- While loops need an exit strategy.
- Updating the loop variable is critical.
The Golden Rule: Indentation
How to Apply Loops
- Identify the goal: Process a list (for) or wait for a change (while).
- Header: End the line with a colon (
:). - 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.
- The colon (:) marks the start of the loop body.
- Indentation defines what code belongs inside the loop.
- Python uses 4 spaces by default.
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.
- Identify logic errors.
- Recognize missing update statements.
Summary & Best Practices
Loop Mastery
- For: Known sequences/ranges.
- While: Unknown durations/conditions.
- Range(n): Stops at n-1.
- Indentation: Mandatory 4 spaces.
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!
- Choose the right loop for the task.
- Always check your indentation.
- Ensure your while loops have an exit.