Else Block ใน Loop (For และ While) จะ Execute หลังจาก Iterations ทั้งหมดเสร็จสิ้น และก่อนที่ Program Flow จะออกจาก Loop Body ไวยากรณ์มีดังนี้:
Syntax
while expr == True:
# statements to be iterated while expr is true
else:
# this statement(s) will be executed after iterations are over
# this will be executed after the program leaves loop body
ตัวอย่าง
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