Translated from https://s16h.medium.com/the-forgotten-optional-else-in-python-loops-90d9c465c830
In this paper, Python Of for-else
and while-else
grammar ,Python One of the least used and often misunderstood features in .
Python Medium for
Circulation and while
Each loop has an optional else
Kit ( Be similar to if
Statement and try
sentence ), If the cycle ends normally , Then the... Will be executed else Kit . let me put it another way , If we do not in any unnatural way (break
、return
Or throw an exception ) Exit loop ,else
The suite will be executed . namely , No, break
sentence , No, return
sentence , Or not in the loop Trigger exception
.
Take a simple example :
In [1]: for i in range(5):
...: print(i)
...: else:
...: print("Iterated over everything :)")
...:
0
1
2
3
4
Iterated over everything :)
In the code above , We traverse range(5)
And print each number . Because we let the loop complete normally , therefore else
The suite will also be executed , also Iterated over everything :)
Be printed out . contrary , If we stop the cycle , For example, use break
sentence , that else
The suite will not be executed :
In [2]: for i in range(5):
...: if i == 2:
...: break
...: print(i)
...: else:
...: print("Iterated over everything :)")
...:
0
1
Be careful , Even if the sequence iterated by the loop is empty ,else
The suite will also be executed ; After all , The loop still completes normally :
In [3]: for i in []:
...: print(i)
...: else:
...: print("Iterated over everything :)")
...:
Iterated over everything :)
in addition , Let's not forget , These also apply to while-else
:
In [4]: i = 0
In [5]: while i <= 5:
...: i += 1
...: print(i)
...: else:
...: print('Yep')
...:
1
2
3
4
5
6
Yep
else
A common use of clause in a loop is to implement a search loop .
Suppose you are searching for an item that meets certain criteria , And additional processing needs to be performed , Or if no acceptable value is found , Causes an error :
for x in data:
if meet_condation(x):
break
else:
# raise error or do addition processing
without else
Clause , You need to set a flag , Then check the flag later , To see if any of the values meet the following conditions :
condition_is_met = False
for x in data:
if meets_condition(x):
condition_is_met = True
if not condition_is_met:
# raise error or do additional processing
It's no big deal , This is what you have to do in many other languages .
however , And Python Like many other features of ,else
Clause can produce more elegant and Pythonic Code for . so to speak , In the example above , Using it can make the code more The Zen of Python-friendly.
There is no situation where you have no choice , Can only be used in a loop else
Clause . You can always use flag Marking and other methods , but else
Clauses usually make the code more elegant and readable . One might think that this is Pythonic Of , It makes the intention clearer , Others may think it is confusing and superfluous !