Python3.x基础学习-while...else

if ... else

一般我们的概念都是 if...else,实际上python还有  while...else用法,大概的作用就是,当while循环走完了就可以走else了,如果没有就不走,比如循环中途遇到了break后

while 条件表达式: 
    --代码--
    --改变计数器的值 --
else:
    --代码 --

举例:

code1:
num = 0
while num<=10:
num+=1
if num==4:
continue #continue不会影响else的执行
print(num,end=' ')
else:
print("--else--")
# 1 2 3 5 6 7 8 9 10 11 --else--

 code2:

num = 0
while num<=10:
    num+=1
    if num==4:
        break #break 后不会执行else
    print(num,end=' ')
else:
    print("--else--")

# 1 2 3
原文地址:https://www.cnblogs.com/johnsonbug/p/12556889.html