In this tutorial, we will learn about different types of loops in Python. We will cover the basics of for, while, and do-while loops.
A loop is a control flow statement that allows code to be executed repeatedly based on a condition.
Python supports two types of loops: for loops and while loops. Although Python does not have a built-in do-while loop, it can be simulated using a while loop.
A for loop is used when the number of iterations is known before entering the loop. The syntax for the for loop is:
for item in iterable:
# Code block to be executed
A while loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:
while condition:
# Code block to be executed
Although Python does not have a built-in do-while loop, it can be simulated using a while loop with a break statement. The syntax for simulating a do-while loop is:
while True:
# Code block to be executed
if not condition:
break
for i in range(1, 11):
print(i, end=' ')
1 2 3 4 5 6 7 8 9 10
i
and initialize it to 1.i = 1
while i <= 5:
print(i, end=' ')
i += 1
1 2 3 4 5
i
and initialize it to 1.i = 1
while True:
print(i, end=' ')
i += 1
if i > 3:
break
1 2 3