Python else

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 ifconditional statement is satisfied that the following statement is executed, otherwise execute elsethe 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 whilewhether complete executed, if interrupted halfway, is not executed else
if the breakexecution 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 whileat a == 4the time break, so you do not execute elsethe statement.

for

for...else...Used to determine forwhether 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()

Guess you like

Origin www.cnblogs.com/dbf-/p/11840008.html