While Loop and For Loop in Python
Introduction
Loops are an essential part of programming, allowing us to execute a block of code multiple times. Python provides two main types of loops: the while loop and the for loop. This article explains these loops with examples.
While Loop
The while loop continues to execute a block of code as long as the condition specified is true. It is used when the number of iterations is not known in advance.
Syntax
while condition: # code to execute
Example
The following example prints numbers from 1 to 5 using a while loop:
# Example of while loop count = 1 while count <= 5: print(count) count += 1
Output:
1 2 3 4 5
For Loop
The for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or a range of numbers.
Syntax
for variable in sequence: # code to execute
Example
The following example prints each element of a list using a for loop:
# Example of for loop numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)
Output:
1 2 3 4 5
Using Range in For Loop
The range() function is commonly used with for loops to iterate over a sequence of numbers. It can take up to three arguments: start, stop, and step.
Example
The following example prints numbers from 0 to 4 using a range:
# Example of for loop with range for i in range(5): print(i)
Output:
0 1 2 3 4
Comparison of While Loop and For Loop
Both while and for loops are used to repeat a block of code, but they are suited for different use cases:
- Use a while loop when the number of iterations is not known in advance and depends on a condition.
- Use a for loop when iterating over a sequence or a range of numbers.
Conclusion
Understanding the differences between while and for loops and knowing when to use them is crucial for efficient programming. Experiment with these examples to gain more confidence.