Loops allow you to execute a block of code multiple times. Python supports both for
and while
loops.
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.
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.
Create a loop that prints all even numbers from 0 to 20.
for
loop and a while
loop?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.