Loops are used to execute a block of code repeatedly. For example, If you want to print the numbers from 1 to 5, you can do it very easily. But, when printing the numbers from 1 to 1000, writing so much code could be hectic. This can be done easily using loops.
The for loop
This loop iterates over sequences such as strings, lists, tuples, sets and dictionaries.
Example 1: iterating over a string
name = 'Python'
for i in name:
print(i)Output:
P
y
t
h
o
nExample 2: iterating over a list
colors = ["Red", "Green", "Blue", "Yellow"]
for color in colors:
print(color)Output:
Red
Green
Blue
YellowYou can also use for loop inside a for loop. For example:
colors = ["Red", "Green", "Blue", "Yellow"]
for color in colors:
print(color)
for i in color:
print(i)Using range() in Loops
If you want to use for loop for a specific number of times, then you can use the range() function.
Syntax:
range(start, stop, step)Example 1:
for n in range(5):
print(n)Output:
0
1
2
3
4
Here loop starts from 0 by default and increments at each iteration.
Example 2:
for n in range(5, 10):
print(n)Output:
5
6
7
8
9Here loop starts from 5 and increments each time up to (but not including) 10.
Example 3:
for n in range(5, 10, 2): # 5 is the start, 10 is the stop (not included), and 2 is the step value.
print(n)Output:
5
7The while loop
The while loop executes a block of code as long as a specified condition is True.
For example:
count = 1
while count < 5:
print(count)
count = count + 1Output:
1
2
3
4Infinite Loop
In an infinite loop, if the condition never becomes False, the loop will keep running forever and never stop on its own.
Example of breaking an infinite loop:
while True:
number = int(input("Enter a positive number: "))
print(number)
if number <= 0:
breakThe break Statement
The break statement stops the loop right away and moves to the code that comes after the loop.
For example:
for i in range(10):
if i == 5:
break
print(i)Output:
0
1
2
3
4The continue Statement
The continue statement skips the remaining part of a loop and moves on to the next iteration of the loop.
For example:
for i in range(10):
if i == 5:
print("Skipping iteration")
continue
print(i)Output of the above code:
0
1
2
3
4
Skipping iteration
6
7
8
9Do-While Loop Equivalent
Python does not have a built-in do-while loop, but similar behavior can be achieved with a while loop.
For example:
while True:
number = int(input("Enter a positive number: "))
print(number)
if number <= 0:
breakThe else Statement with Loops
In Python, you can use an else block with both for and while loops.
This special usage allows the execution of a block of code after the loop completes all iterations.
Syntax:
for variable in sequence:
# Code to execute for each iteration
else:
# Code to execute after the loop finishesThe else block is executed only when the loop successfully completes its iterations. If a break statement exits the loop, the else block will be skipped.
Example with for loop:
for i in range(5):
print(i)
else:
print("Loop finished without break")Output:
0
1
2
3
4
Loop finished without breakExample with break:
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop finished without break")Output:
0
1
2In this case, the else block is not executed because the loop was stopped with break.
Example with while loop:
i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop finished without break")Output:
0
1
2
3
4
Loop finished without breakExample with break:
i = 0
while i < 5:
if i == 3:
break
print(i)
i += 1
else:
print("Loop finished without break")Output:
0
1
2As with the for loop, the else block in a while loop runs only if the loop ends normally (not via break).
Special Scenarios
Empty Loops:
If the loop body does not execute (e.g., an empty sequence or a while loop condition is False initially), the else block will still execute.
for x in []:
print("This will not execute.")
else:
print("Loop completed successfully.")Output:
Loop completed successfully.Nested Loops:
The else block applies only to the loop it is associated with. In nested loops, it executes when the specific loop completes successfully.
for i in range(2):
for j in range(2):
if i == j:
print(f"Breaking inner loop at i={i}, j={j}")
break
else:
print(f"Outer loop iteration {i} completed without breaking.")Output:
Breaking inner loop at i=0, j=0
Outer loop iteration 1 completed without breaking.👉 Next tutorial: Python Functions