Loops allow you to execute a block of code multiple times. Python makes looping very intuitive, especially when dealing with ranges of numbers or items in a list.
1. The for Loop
In Python, the for loop is primarily used for iterating. Instead of the "initialize-condition-increment" style found in C, Python's for loop iterates over a sequence (like a list or a range of numbers).
range(start, stop, step): A built-in function that generates a sequence of numbers.range(5)-> 0, 1, 2, 3, 4range(1, 6)-> 1, 2, 3, 4, 5
2. The while Loop
The while loop repeats as long as a certain condition remains True. It is best used when you don't know exactly how many times you need to loop.
# --- FOR LOOP ---
print("For Loop (1 to 5):")
for i in range(1, 6):
print(i, end=" ") # 'end' keeps the output on one line
print("\n\nIterating over a string:")
for letter in "PYTHON":
print(letter)
# --- WHILE LOOP ---
print("\nWhile Loop:")
count = 5
while count > 0:
print(f"T-minus {count}")
count -= 1 # Important: Update the condition!
print("Blast off! 🚀")3. Loop Control: break and continue
break: Stops the loop entirely.continue: Skips the rest of the current iteration and jumps to the next one.
for num in range(1, 10):
if num == 5:
continue # Skip 5
if num == 8:
break # Stop at 8
print(num)