Member-only story
In Python, loops are control flow structures that allow you to repeatedly execute a block of code. They are used to iterate over sequences, such as lists, strings, and other iterable objects, to perform a set of operations multiple times. Python supports two main types of loops: for
loops and while
loops.
1. For Loop with Range:
# This loop iterates over a range of numbers from 0 to 4.
for i in range(5):
print(i)
2. For Loop with List:
# This loop iterates over each element in the list fruits.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
3. While Loop:
# This while loop continues executing as long as the condition count < 5 is true.
count = 0
while count < 5:
print(count)
count += 1
4. Nested For Loops:
# This example shows nested loops,
# with the outer loop iterating 3 times and the inner loop iterating 2 times for each outer iteration.
for i in range(3):
for j in range(2):
print(i, j)
5. Looping Through Dictionary:
# This loop iterates over the key-value pairs of a dictionary…