Skip to content

Loops

This documentation will guide you to get started quickly. In Python, loops are structures that allow you to execute a block of code repeatedly until a condition is met. There are two main types of loops: for and while. The for loop iterates over a sequence (like a list, tuple, or string), while the while loop executes code while a condition is true.

The for loop is ideal for iterating over the elements of a sequence (list, tuple, string, etc.).

loop.py
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
# This code will print each fruit from the list.

The while loop executes a block of code while a condition is true.

loop.py
counter = 0
while counter < 10:
    print(counter)
    counter += 1
# Will print numbers from 0 to 9.
  • for : Better for iterating over elements of a sequence when the number of iterations is known in advance.
  • while : Better for executing a block of code while a condition is true, when the number of iterations is not known in advance.