Summary of the usage of else in the Python loop
- 2020-05-12 02:46:55
- OfStack
preface
This article discusses Python
for…else
and
while…else
These are the least used and most misunderstood features of Python.
In the Python
for
,
while
There's an optional one for each of these loops
else
Branch (similar to
if
Statements and
try
Statement), which is executed after the loop iteration has normally completed. In other words, if we do not exit the loop in any other way than the normal way, then
else
The branch will be executed. It's not in the circulation
break
Statement, no
return
Statement, or no exception occurs.
Let's look at a detailed usage example.
1. Regular use of if else
x = True
if x:
print 'x is true'
else:
print 'x is not true'
2. if else
Here,
while…else
0
Can be used as a 3 - bit operator.
mark = 40
is_pass = True if mark >= 50 else False
print "Pass? " + str(is_pass)
3. Use with for keyword 1
In the following cases,
else
The following code block will be executed:
1.
for
The statements in the loop are executed
2,
for
The statements in the loop are not
break
Statements to interrupt
# print `For loop completed the execution`
for i in range(10):
print i
else:
print 'For loop completed the execution'
# Don't print `For loop completed the execution`
for i in range(10):
print i
if i == 5:
break
else:
print 'For loop completed the execution'
4. Use with while keyword 1
Similarly, when the following conditions are met,
else
The following code block will be executed:
1.
while
The statements in the loop are executed
2,
while
The statements in the loop are not
break
Statements to interrupt
# print `While loop execution completed`
a = 0
loop = 0
while a <= 10:
print a
loop += 1
a += 1
else:
print "While loop execution completed"
# Don't print `While loop execution completed`
a = 50
loop = 0
while a > 10:
print a
if loop == 5:
break
a += 1
loop += 1
else:
print "While loop execution completed"
5. Use with try except 1
and
try except
If you don't throw an exception,
else
The statement can be executed.
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'
f.close()
conclusion
The usage of else in the loop statement in Python is basically concluded. This article has a definite reference value for you to learn or use Python, and I hope it can be helpful to you. If you have any questions, you can leave a message to communicate.