Loops allow your code to repeat tasks automatically. Python has two main types of loops: for and while. Each is useful in different situations.
What is a loop?
A loop runs a block of code multiple times. This avoids writing the same code over and over.
Like conditional statements, loops require a colon : and proper indentation to define the code block.
The for loop
A for loop is best when you know how many times to repeat or when working with a sequence (like a list or range).
Use range() to loop a specific number of times:
for i in range(5):
print(i)
This prints:
0
1
2
3
4
Loop over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
The for loop is safe because it stops automatically when the sequence ends.
The while loop
A while loop repeats as long as a condition is True.
count = 0
while count < 5:
print(count)
count = count + 1
This prints the same numbers: 0 to 4.
Always update the condition inside the loop (here, count = count + 1). Forgetting this creates an infinite loop that never stops.
When to use for vs while
- Use
forwhen you know the number of repetitions or have a sequence to iterate over. It is simpler and safer. - Use
whilewhen the number of repetitions depends on a condition that might change during the loop.
Using break to exit early
Both loops support break to stop early:
for i in range(10):
if i == 5:
break
print(i)
This prints 0 to 4 and then stops.
Common examples
Print even numbers from 0 to 10 with a for loop:
for i in range(0, 11, 2):
print(i)
Simple countdown with while:
n = 5
while n > 0:
print(n)
n = n - 1
print("Done!")
Important notes
- Indentation defines the loop body.
-
forloops are less likely to create infinite loops. - Always plan how the loop will end when using
while.
Quick summary
-
forloops are great for known sequences or counts. -
whileloops continue based on a condition. - Use
breakto exit a loop early. - Proper planning prevents infinite loops.
Practice both types with small examples. Loops are essential for handling repetition in Python programs.
Top comments (0)