Python Loops (For and While Loops)
Loops allow you to execute a block of code multiple times. Python supports both for and while loops.
For Loop
The for loop is used to iterate over a sequence (such as a list, tuple, or string):
for i in range(5):
print(i)
This will print the numbers 0 through 4.
While Loop
The while loop runs as long as a condition is True:
count = 0
while count < 5:
print(count)
count += 1
This will also print the numbers 0 through 4.
Activity
Try It Yourself!
Create a loop that prints all even numbers from 0 to 20.
Quick Quiz
Quick Quiz
- What is the difference between a
forloop and awhileloop? - How do you stop a loop early in Python?
Answers: A for loop iterates over a sequence, while a while loop runs as long as a condition is True. Use break to stop a loop early.