Loops help you repeat the same task multiple times without writing the same code again and again.
Loops are used to execute a block of code repeatedly until a condition becomes false.
A for loop is used to iterate over a sequence like list, string, or range.
for i in range(5):
print(i)
Output:
0 1 2 3 4
A while loop runs as long as the condition is true.
count = 1
while count <= 5:
print(count)
count += 1
The range() function generates a sequence of numbers.
for number in range(1,6):
print(number)
break is used to stop the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
continue skips the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i)
A loop inside another loop is called a nested loop.
for i in range(3):
for j in range(2):
print(i,j)
Python mainly has two loops: for loop and while loop.
range() creates a sequence of numbers for looping.
Yes, one loop can be placed inside another loop.