Skip to content

if statement in for loop Python | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading