What are the different types of loops in Python?

In Python, there are two main types of loops:

  1. for loops: for loops are used to iterate over a collection of items, such as a list, tuple, or string. The basic syntax for a for loop is as follows:
yaml
for 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:

css
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
  1. while loops: while loops are used to repeatedly execute a code block as long as a certain condition is true. The basic syntax for a while loop is as follows:
python
while condition: # code block to be executed

For example, you can use a while loop to print out the numbers from 1 to 10:

python
x = 1 while x <= 10: print(x) x += 1

Additionally, Python provides two more types of loops:

  1. 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 a do-while loop is as follows:
python
while True: # code block to be executed if not condition: break
  1. 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.
python
for 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.