Preface
This article discusses Python's for…else
and while…else
other syntax, which is one of the most common and misunderstood grammatical features in Python.
In Python for
, the while
Loop has an optional else
branch (like the if
statement and try
statement) that executes after the loop iteration is completed normally. In other words, if we do not exit the loop in any way other than the normal way, then the else
branch will be executed. That is, there is no break
statement, no return
statement, or no exception in the loop body.
Let's take a look at the detailed usage examples below.
I. GENERAL if ELSE usage
x = Trueif X:print ' x is True ' Else:print ' X was not true '
Second, if else quick usage
This if else
can be used as a ternary operator.
Mark = 40is_pass = True If Mark >= or Falseprint "pass?" + str (is_pass)
Third, with the FOR keyword one
The else
next block of code is executed when the following conditions are met:
1, for
the statement execution in the loop completes
2, for
the statement in the loop is not interrupted by the break
statement
# print ' For loops completed the execution ' for I in range: Print Ielse:print ' For loop completed the execution ' # does not print ' for Loop completed the execution ' for I in range: print i if i = = 5:breakelse:print ' For loop completed the execution '
Iv. with the While keyword
Similar to the above, the else
next block of code is executed when the following conditions are met:
1, while
the statement execution in the loop completes
2, while
the statement in the loop is not interrupted by the break
statement
# print ' While loop execution completed ' a = 0loop = 0while a <= 10:print a loop + = 1 A + = 1else:print "While loop execut Ion completed "# does not print ' while loop execution completed ' a = 50loop = 0while a > 10:print a If loop = = 5:break A + = 1 loop + = 1else:print "While loop execution completed"
V. Use with try except
and try except
when used together, if the exception is not thrown, else
the statement can be executed.
file_name = "Result.txt" try:f = open (file_name, ' R ') except Ioerror:print ' cannot open ', File_nameelse: # executes only I F file opened properly print file_name, ' has ', Len (F.readlines ()), ' Lines ' f.close ()
Summarize
About the use of else in the circular statement in Python summary to this is basically the end of this article for everyone to learn or use Python or have a certain reference value, hope to everyone can help, if there are questions you can message exchange.