Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ทำไม Python จึงมี Else Clause ใน Loops?

คุณสมบัติเฉพาะของ Python หนึ่งคือความสามารถในการใช้ Else Clause ร่วมกับ Loop คุณสมบัตินี้ไม่พบในภาษาอย่าง C/C++ หรือ Java

ปกติ Body ของ Loop จะ Execute ซ้ำๆ ควบคุมโดย Looping Condition หลังจากนั้น Statements หลังมันจะเริ่ม Execute ใน Python Loop Else Block จะ Execute หลังจาก Iterations ทั้งหมดจบ และก่อนที่ Program จะออกจาก Loop ให้ดูตัวอย่างต่อไปนี้:

ตัวอย่าง

for x in range(5):
    print('inside body of loop', x)
else:
    print('else block of loop')
print('outside loop')

ผลลัพธ์

ผลลัพธ์แสดง Else Block ถูก Execute ก่อนที่ Loop Block จะถูกจากไป

inside body of loop 0
inside body of loop 1
inside body of loop 2
inside body of loop 3
inside body of loop 4
else block of loop
outside loop