In Python, there are two main types of loops:
for
loops:for
loops are used to iterate over a collection of items, such as a list, tuple, or string. The basic syntax for afor
loop is as follows:
yamlfor variable in collection:
# code block to be executed
For example, you can use a for
loop to iterate over the elements of a list and print them out:
cssfruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
while
loops:while
loops are used to repeatedly execute a code block as long as a certain condition is true. The basic syntax for awhile
loop is as follows:
pythonwhile condition:
# code block to be executed
For example, you can use a while
loop to print out the numbers from 1 to 10:
pythonx = 1
while x <= 10:
print(x)
x += 1
Additionally, Python provides two more types of loops:
do-while
loop:do-while
loop is not present in python as a keyword, but can be implemented using while True and break. The basic syntax for ado-while
loop is as follows:
pythonwhile True:
# code block to be executed
if not condition:
break
for-else
loop:for-else
loop allows you to specify a code block that will be executed after the for-loop completes its execution. This can be useful for tasks like searching for an element in a list, and then returning a result based on whether the element was found or not.
pythonfor i in range(5):
if i == 3:
print("Found")
break
else:
print("Not found")
So, in summary, Python provides for
, while
and for-else
loops and you can use while True
and break
for implementing do-while
loop.
Social Plugin