Else clause after for and while loops in python

(Comments)

Some of us are not aware of the else clause after the for and while loops in python. Take this example

weekly_trends = {1000, 1100, 1500, 1250}
is_abnormal = False
for value in weekly_trends:
    if value  >  1400:
        is_abnormal = True

        break;
if not is_abnormal:
    print("no abnormalities found")

The above program is maintaining a flag to check if any element has a value greater than 1400, if found, it is setting the flag is_abnormal to True, then executing the break statement. And, after the for loop, we are checking the flag and if it is not set to true, we are printing "no abnormalities found".

Instead of maintaining a separate flag, we can make use of the else clause after the for loop as shown below.

for value in weekly_trends:
    if value  >  1400:
        break;
else:
    print("no abnormalities found")

So, here, the control will come to else block, only when the break statement is not executed, and this would serve the same purpose without the additional flag logic.

Comments

Recent Posts

Archive

2022
2021
2020
2019
2018
2017
2016
2015
2014

Tags

Authors

Feeds

RSS / Atom