Loops are used to repeatedly execute a block of code as long as a specified condition is met. There are two main types of loops in Python: for
loops and while
loops. Each has its own syntax and use cases.
The for
loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range). The basic syntax of a for
loop is as follows:
for variable in sequence:
# block of code to be executed
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
The range()
function is often used with for
loops to generate a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
You can nest for
loops to iterate over multiple sequences.
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
Output:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
The while
loop in Python repeatedly executes a block of code as long as a given condition is true. The basic syntax of a while
loop is as follows:
while condition:
# block of code to be executed
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Be careful with while
loops as they can create infinite loops if the condition never becomes false. You can use a break
statement to exit the loop.
while True:
print("This is an infinite loop!")
break
Output:
This is an infinite loop!
The break
statement is used to exit a loop prematurely.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
The continue
statement skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output:
1
3
5
7
9
You can use an else
clause with both for
and while
loops. The else
block will be executed when the loop terminates naturally (i.e., not by a break
statement).
for i in range(5):
print(i)
else:
print("Loop finished without break")
while count < 5:
print(count)
count += 1
else:
print("While loop finished without break")
Output:
0
1
2
3
4
Loop finished without break
0
1
2
3
4
While loop finished without break
for
Loop: Used for iterating over a sequence (list, tuple, string, range, etc.).while
Loop: Repeatedly executes a block of code as long as a condition is true.break
: Exits the loop.continue
: Skips the rest of the code inside the loop for the current iteration.else
Clause: Executes when the loop terminates naturally.