Python

for ... else ...

for 循环执行完时, 且该for 循环没有被 break语句终止,才运行 else语句

Eg:

for i in range(1, 5):
    if i == 4:
        print("Not break")
else:
    print("Run else")

"""输出 
Not break
Run else
"""

for i in range(1, 5):
    if i == 4:
        print("break")
        break
else:
    print("Run else")
  
"""输出 
Not break
"""

while ... else ...

for循环类似;当while循环执行完时,且未被break语句终止,才运行else语句

Eg:

i = 0
while i <= 5:
    i += 1
    if i == 4:
        print("Not break")
else:
    print("Run else")
    
"""输出 
Not break
Run else
"""

i = 0
while i <= 5:
    i += 1
    if i == 4:
        print("break")
        break
else:
    print("Run else")
    
"""输出 
break
"""

try ... else ...

try 语句块中没有异常抛出时,才运行else语句,else语句抛出的异常不会由前面的except语句处理。

(~﹃~)~zZ

???

评论

This is just a placeholder img.