for loop with if statement in python

Here is an example of using for loop with if statement in Python:

main.py
for i in range(10):
    if i % 2 == 0:
        print(i, "is even")
    else:
        print(i, "is odd")
104 chars
6 lines

Output:

main.py
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
95 chars
11 lines

In this example, the for loop iterates through a range of 10 numbers. The if statement checks if the current number i is even or odd and prints the corresponding message. The % operator is used to check if i is divisible by 2.

You can replace the range(10) with any iterable object in Python, such as a list or a tuple. The if statement can also be modified according to your specific condition.

related categories

gistlibby LogSnag