1. What are Loops?
In programming, loops are control flow constructs that allow you to repeat a block of code multiple times. This is essential for traversing collections, automating tasks, and logic building. Python supports two main types of loops: for loops (for iterating over a predetermined sequence) and while loops (for repeating actions as long as a condition evaluates to True).
2. The `for` Loop and `range()`
A for loop iterates over elements in any sequence (like a list or text string) or a range of numbers. The range(start, stop, step) function generates numbers starting from start (inclusive), up to but not including stop (exclusive), incrementing by step.
# Iterate from 0 up to 4 (5 is excluded)
for i in range(5):
print(i) # Prints: 0, 1, 2, 3, 4
# Iterate from 1 to 10 with step 2 (odd numbers only)
for number in range(1, 11, 2):
print(number) # Prints: 1, 3, 5, 7, 9
3. The `while` Loop
A while loop executes code repeatedly as long as its condition remains True. It is crucial to modify the condition state inside the loop block; otherwise, the loop will run forever, creating an **infinite loop** that crashes your system.
count = 5
while count > 0:
print("Countdown:", count)
count -= 1 # Decrement count so condition eventually becomes False
print("Blastoff!")
4. Loop Interruption: break and continue
You can fine-tune loops using control statements:
break: Terminates the loop immediately and jumps to the code following the loop block.continue: Skips the remaining code inside the current loop iteration and moves directly to the next loop cycle.
# Skip 3, stop loop at 7
for n in range(1, 10):
if n == 3:
continue # Skip printing 3
if n == 8:
break # Stop loop at 8
print(n)
5. Common Beginner Mistakes
⚠️ Watch out for these mistakes:
- Infinite Loops: Forgetting to increment the loop control counter variable inside a
whileloop, resulting in a loop that never terminates. - Off-by-One Range Boundary: Forgetting that
range(1, 10)runs from 1 to 9, not 10. The ending value is always excluded. - Incorrect Indentation: Code that you want inside the loop must be indented. Placing code flush with the margin means it will only execute after the loop ends.
Mini Practice: Squaring Calculator
Write a script that uses a for loop to print the squares of each number from 1 through 10. However, use the continue statement to skip printing the square if it is an odd number (only print even squares).
Practice complete!
Excellent. Loops are under control. Test your knowledge below to unlock data structures.
Test Your Understanding
1. Which numbers are generated by `range(1, 5)` in a loop?
2. What does the `continue` statement do when reached inside a loop?
3. What is a key danger of using a `while` loop?
🚀 Progression
You have unlocked data collections! Next, you'll learn how to organize, access, and manipulate sequence lists using **Lists, Tuples, and Sets**.