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.).
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.
counter = 0while counter < 10: print(counter) counter += 1
# Will print numbers from 0 to 9.
Key Differences
Section titled “Key Differences”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.