Else statements in the Python loop
Most programming languages have conditional judgments, such as if ... else, in the larger language, else is usually only present in the conditional judgment statement, with the IF statement, but in Python, the else can appear in the for, WHI, as well as the IF condition judgment. In a circular statement such as Le.
Let's look at an example:
12345678910 |
s
= [
"a111"
,
"b222"
,
"c333"
,
"d444"
,
"e555"
]
found
= False
for c
in s:
if c.startswith(
"c"
):
found
= True
print u
"发现以字母c开头的项"
break
if not found:
print u
"没有发现以字母c开头的项"
|
Do a loop, and if you find a letter that satisfies the condition, print out a hint, and then print out another message if you don't see it in the loop. We need to set an additional variable to record whether the target character (the found variable in the program) is found, and then make an if judgment after the loop is complete.
The above notation is certainly possible, but if we use the Else statement in the loop, the code will be more concise and clear. Like what:
1234567 |
s
= [
"a111"
,
"b222"
,
"c333"
,
"d444"
,
"e555"
]
for c
in s:
if c.startswith(
"c"
):
print u
"发现以字母c开头的项"
break
else
:
print u
"没有发现以字母c开头的项"
|
In this case, it is not necessary to record the additional variables that are found, and it is no longer necessary to make the If judgment after the loop is completed, but the effect is the same as the first code.
In Python, for ... else means that the statement in for is no different from normal, while the statement in else is executed when the loop is executed normally (that is, for not breaking out by break), while ... else is the same.
If you replace break with continue, the effect is that the statement in else is definitely executed, and some occasions are an interesting usage.
Python for Else statement