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.
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.
while condition: # code to execute
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
The for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or a range of numbers.
for variable in sequence: # code to execute
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
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.
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
Both while and for loops are used to repeat a block of code, but they are suited for different use cases:
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.