For Loop and While Loop in Python
Loops are a fundamental part of programming that allow you to execute a block of code repeatedly. Python provides two types of loops: the for loop and the while loop. Each has its own use cases and benefits.
For Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence. It’s especially useful when you know in advance how many iterations are required.
Syntax:
for variable in sequence:
# code to execute
Example 1: Iterating Through a List
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Using range()
in a For Loop
The range() function is commonly used with for loops to generate a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 3: For Loop with an Else Block
You can also have an else block with a for loop, which executes when the loop completes its iterations without breaking.
for i in range(3):
print(i)
else:
print("Loop finished!")
Output:
0
1
2
Loop finished!
While Loop
The while loop repeatedly executes a block of code as long as the given condition is True. It’s generally used when the number of iterations is not known beforehand.
Syntax:
while condition:
# code to execute
Example 1: Simple While Loop
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Example 2: While Loop with Break Condition
The break statement is used to exit the loop when a specific condition is met.
count = 0
while count < 10:
if count == 5:
break
print(count)
count += 1
Output:
0
1
2
3
4
Example 3: While Loop with an Else Block
Just like the for loop, you can also use an else block with a while loop. The else block runs when the loop condition becomes false, unless the loop is terminated by a break.
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop finished!")
Output:
0
1
2
Loop finished!
Key Differences Between For and While Loops
- For Loop: Ideal for iterating over a sequence of known length or when you know the number of iterations beforehand.
- While Loop: Useful when you want to continue executing a block of code until a certain condition is met, without knowing in advance how many iterations it will take.
Summary
- For Loops: Use them to iterate over a collection or a specific range of values.
- While Loops: Use them when the number of iterations isn’t known upfront, and the loop depends on a condition being met.