循环中的else块(以及同时)在循环的所有迭代完成之后且程序流退出循环主体之前执行。语法如下-
while expr==True: #statements to be iterated while expr is true. else: #this statement(s) will be executed afteriterations are over
#这将在程序离开循环体后执行
for x in range(6): print (x) else: print ("else block of loop") print ("loop is over")
输出结果
输出如下所示-
0 1 2 3 4 5 else block of loop loop is over