if statement in for loop Python | Example code

Let’s see how you can use the if-else conditional statement with for loop in python.

squares = []
remain = []
for i in range(10):
    if i % 2 == 0:
        squares.append(i ** 2)
    else:
        remain.append(i ** 2)

print(squares)
print(remain)

Output:

if statement in for loop Python

Else block is executed statement in for loop Python

for i in range(1, 4):
    print(i)
else:
    print("No Break")

Output:

1
2
3
No Break

Else block is NOT executed using break keyword

for i in range(1, 4):
    print(i)
    break
else:
    print("No Break")

Output: 1

Do comment if you have any doubts and suggestions on this Python code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.