Objective
This article discusses the for…else
syntax of Python and while…else
so on, which is one of the most common and misunderstood grammatical features in Python.
The loops in for
python while
have an optional else
branch (like if
statements and try
statements) that are executed after the loop iteration is completed normally. In other words, if we are not exiting the loop in any way other than the normal way, then the else
branch will be executed. That is, there are no statements in the loop, break
no return
statements, or no exceptions.
Let's take a look at the detailed usage examples below.
One, the general if else usage
x = True
if x:
print ' x is True '
else:
print ' x is not true '
Two, if else quick usage
This if else
can be used as a ternary operator.
Mark =
Is_pass = True if Mark >= else False
print "pass?" + str (is_pass)
Third, with the FOR keyword one
The else
next code block is executed when the following conditions are true:
1, for
the execution of the statement in the loop completes
2, for
the statement in the loop is not interrupted by the break
statement
# print ' For loop completed the execution ' to
I in range: print
i
else: print ' for
Loop completed the ex Ecution '
# do not print ' For loop completed the execution ' to
I in range:
print i
if i = 5:
break
else:
print ' For loop completed the execution '
Four, with while keyword one
Similar to the above, the else
next code block is executed when the following conditions are true:
1, while
the execution of the statement in the loop completes
2, while
the statement in the loop is not interrupted by the break
statement
# print ' While loop execution completed '
a = 0
loops = 0 while
a <=:
print a
loop + = 1
A + = 1
else:
print "While loop execution completed"
# does not print ' while loop execution completed '
a =
loop = 0
while a >:
print a
if loop = = 5:
break
A + + 1
loop + = 1
else:
print "while loo P Execution Completed "
V. Use with try except
and try except
when used together, else
the statements in can be executed if the exception is not thrown.
file_name = "Result.txt"
try:
f = open (file_name, ' R ')
except IOError:
print ' cannot open ', File_ Name
else:
# executes only if file opened properly
print file_name, ' has ', Len (F.readlines ()), ' lines ' C32/>f.close ()
Summarize
About the usage of else in the loop in Python summary to this is basically the end, this article for everyone to learn or use Python or have a certain reference value, hope to be helpful to everyone, if you have questions you can message exchange.