Loops are an essential part of programming, allowing you to repeat a block of code multiple times. In Python, there are two types of loops: while loops and for loops. In this article, we will explore how to use these loops effectively in Python.
While Loops
While loops are defined using the while
keyword and repeat their block of code until a certain condition is met. Here is an example of an infinite while loop:
condition = True
while condition:
print("The condition is True")
To exit the loop, we need to change the condition. Let’s modify the previous example to exit the loop after the first iteration:
condition = True
while condition:
print("The condition is True")
condition = False
print("After the loop")
In this case, the first iteration is executed as the condition is initially True
. On the second iteration, the condition is evaluated as False
, and the loop is exited.
It’s common to use a counter variable to limit the number of iterations. For example, let’s iterate the loop 10 times:
count = 0
while count < 10:
print("The condition is True")
count += 1
print("After the loop")
For Loops
For loops allow us to execute a block of code a predetermined number of times, without the need for a separate counter variable. We can iterate over a list of items using a for loop. Here’s an example:
items = [1, 2, 3, 4]
for item in items:
print(item)
We can also iterate a specific number of times using the range()
function:
for item in range(4):
print(item)
In this example, range(4)
creates a sequence starting from 0 with 4 items: [0, 1, 2, 3]
.
To access both the index and the item in the loop, we can use the enumerate()
function:
items = [1, 2, 3, 4]
for index, item in enumerate(items):
print(index, item)
Break and Continue
Both while
and for
loops can be interrupted using two special keywords: break
and continue
.
The continue
keyword stops the current iteration and moves on to the next one. Here’s an example:
items = [1, 2, 3, 4]
for item in items:
if item == 2:
continue
print(item)
In this example, the number 2 is skipped and the loop continues with the next iteration.
The break
keyword, on the other hand, completely stops the loop and moves on to the next instruction after the loop. Here’s an example:
items = [1, 2, 3, 4]
for item in items:
if item == 2:
break
print(item)
In this example, the loop is terminated after encountering the number 2.
Loops are powerful tools in Python for automating repetitive tasks. By understanding the different types of loops and their functionalities, you can write more efficient and concise code.