Interesting talk about python for and else statements

  • 2021-07-09 08:27:06
  • OfStack

My wife called her husband who was a programmer: "Buy 1 kg of steamed buns on the way back from work. If you see watermelons, buy one." That night, the programmer's husband entered the house with a steamed stuffed bun in his hand... The wife angrily said, "Why did you buy a steamed stuffed bun?" Husband replied: "Because I saw the watermelon seller."

Most readers may know the joke that programmers buy watermelons. This article written today has a definite relationship with this joke.

Any programming language provides an if... else... statement to do one thing if (if) meets the criteria, and another thing (else) if not:


if a==b:
print("true")
else:
print("false")

However, in Python, else can not only be used with if, but also has another unique syntax, for … else … In addition, it can also be used in combination with while, try … except, for example:


for i in range(3):
print(i)
else:
print("end")
>>>
0
1
2
end

However, you will find that for … else … and if … else … behave differently. According to past experience, the code in for statement block does not execute else, and vice versa.

What we see, however, is just the opposite. The for loop ends and then the else block is executed, which is interesting. if … else … translated into vernacular is if … otherwise …, while for … else … translated into vernacular is until … and then …, why not write it into the sentence pattern of for … then …? Isn't this better understood?

In addition, the else statement block is executed even if the for loop traverses an empty list.


for i in []:
print(i)
else:
print("end")
>>>
end

Continue to explore, what will happen if we terminate the for loop prematurely with break?


for i in range(3):
print(i)
if i % 2 == 0:
break
else:
print("end")
>>>
0

When the loop encounters an break exit, the entire statement ends and the else statement block is not executed.

To sum up, we can conclude that the else block will only be executed if break is not encountered in the loop. At this point, you should understand that what is really used with else is break in the for loop, and break... else... are the two mutually exclusive conditions

Why did the father of Python come up with such a grammar sugar? This is something we ordinary people can't understand. However, "Zen of python" tells us the answer: "Although that way may not be obvious at unless you 're Dutch.".

In normal development, there are really few application scenarios of for... else..., but using for else in the following scenario is really a usage of pythonic.

When you use for loop to iterate to find an element in the list, if you find it, you will exit the loop immediately. If you need to notify the caller in another form (such as exception) after iteration, for... else... is undoubtedly the best choice.


# https://stackoverflow.com/a/9980752/1392860
for i in mylist:
if i == target:
break
process(i)
else:
raise ValueError("List argument missing terminal flag.")

If you don't use for... else..., you also need to create a temporary tag variable to mark whether it has been found or not


found = False
for i in mylist:
if i == target:
found = True
break
process(i)
if not found:
raise ValueError("List argument missing terminal flag.")

When you want to find something in your room, stop searching as long as you find it anywhere. But if we have searched the whole room and haven't found what we want, we need to tell people that we are sorry, but there is nothing you are looking for here. Use for in this case... else, otherwise, I'm afraid it will only cause misoperation.


Related articles: