How to Add Condition in For Loop Python
In Python, the for loop is a fundamental construct used to iterate over a sequence of elements, such as a list, tuple, or string. While the basic for loop allows you to iterate through each element in a sequence, you may want to add conditions to control the flow of the loop. This article will guide you on how to add conditions in a for loop in Python.
The primary way to add a condition in a for loop is by using an if statement within the loop. This allows you to execute a block of code only if a certain condition is met. Let’s take a look at an example:
“`python
for i in range(1, 11):
if i % 2 == 0:
print(f”{i} is an even number”)
“`
In this example, we are iterating over a range of numbers from 1 to 10. The if statement checks if the current number is even (i.e., divisible by 2 without a remainder). If the condition is true, the loop will print the number as an even number.
You can also use the `continue` statement to skip the rest of the code in the loop and move on to the next iteration if a certain condition is met. Here’s an example:
“`python
for i in range(1, 11):
if i % 2 != 0:
continue
print(f”{i} is an even number”)
“`
In this modified example, we are skipping all odd numbers using the `continue` statement. As a result, only even numbers will be printed.
Furthermore, you can add conditions to control the loop’s termination. For instance, you can use a `break` statement to exit the loop prematurely if a specific condition is met. Here’s an example:
“`python
for i in range(1, 11):
if i == 5:
print(f”Loop terminated at number {i}”)
break
print(f”{i} is less than 5″)
“`
In this example, the loop will terminate when the number reaches 5, as the `break` statement is executed when the condition is met.
To summarize, adding conditions in a for loop in Python can be achieved using if statements, continue statements, and break statements. By combining these techniques, you can control the flow of your loops and execute specific blocks of code based on your requirements.