In Python, looping is essentially how you tell the computer, "Keep doing this until I say stop" or "Do this for every item in this list." There are two primary ways to handle this: for loops and while loops.
1. The for Loop
The for loop is your "go-to" when you know exactly how many times you want to run a block of code, or when you want to iterate over a collection (like a list, string, or range of numbers).
Iterating over a range
To repeat something a specific number of times, use the range() function.
Python
# This will print numbers 0 through 4
for i in range(5):
print(f"Iteration number: {i}")
Iterating over a list
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love eating {fruit}s!")
2. The while Loop
A while loop is used when you want to keep running as long as a specific condition is True. It's great for situations where you don't know ahead of time when the loop will end (like waiting for user input).
Python
count = 1
while count <= 3:
print(f"Count is {count}")
count += 1 # Important: increment count so the loop eventually ends!
3. Loop Control: break and continue
Sometimes you need to change the behavior of the loop while it's running:
break: Exits the loop entirely, even if the condition is still true.
continue: Skips the rest of the current block and jumps back to the start of the next iteration.
Example: Using break
Python
while True:
name = input("Type 'exit' to stop: ")
if name == "exit":
break
print(f"Hello, {name}!")