Loops are used to execute a block of code repeatedly. Python provides two types of loops: for loop and while loop.
The for loop is used to iterate over a sequence (like a list, tuple, string, or range).
# Using for loop to iterate over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
The while loop repeats as long as the given condition is True
.
# Using while loop to print numbers i = 1 while i <= 5: print(i) i += 1
A loop inside another loop is called a nested loop. Itβs often used to work with multi-dimensional data structures like lists of lists.
# Using a nested loop to iterate over a matrix matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: for item in row: print(item, end=" ") print() # New line after each row
You can control the flow of loops with break and continue statements:
# Using break to stop the loop for i in range(10): if i == 5: break print(i) # Using continue to skip the current iteration for i in range(10): if i == 5: continue print(i)
while
loop eventually becomes False
, otherwise, the loop will run indefinitely.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!