Python else
else can be used with other statements to complete the conditional
most common is if...else...
, of course, there are other statements may be blended else use
if
if...else...
It is the easiest condition to determine
if the if
conditional statement is satisfied that the following statement is executed, otherwise execute else
the following statement
a = True
b = False
if a:
print('a is true')
else:
print('a is false')
elif
elif:
Equivalent to else:if:
that is:
a = True
b = False
if b:
print('b is true')
else:
if a:
print('b is false, a is true')
else:
print('a and b are false')
equal:
a = True
b = False
if b:
print('b is true')
elif a:
print('b is false, a is true')
else:
print('a and b are false')
while
while...else...
Used to determine while
whether complete executed, if interrupted halfway, is not executed else
if the break
execution is not performed else
Example:
def main():
a = 0
while a < 5:
a += 1
print(a)
if a == 4:
break
else:
print('a >= 5')
if __name__ == '__main__':
main()
Because while
at a == 4
the time break
, so you do not execute else
the statement.
for
for...else...
Used to determine for
whether the integrity is interrupted if she is not performed else
Example:
def main():
for i in range(5):
print(i)
if i == 3:
return
else:
print('i > 4')
if __name__ == '__main__':
main()
try
try...else...
Procedures used to determine whether the error, if error does not execute else
Python exception handling <- Click to view
an example:
def main():
try:
a
except Exception as e:
print('An error occur', e)
# 程序未报错执行
else:
print('一切正常')
# 程序报不报错都执行
finally:
print('运行结束')
if __name__ == '__main__':
main()