วิชาภาษาไพทอน (python)

การใช้คำสั่ง while

การใช้งานคำสั่ง while loop เป็นคำสั่งที่เป็นการทำงานแบบวนรอบอย่างง่าย จะทำงานวนรอบไปเรื่อยๆ จนกว่าเงื่อนไขจะเป็นเท็จถึงจะออกจาก loop

ภายใน while  เป็นเงื่อนไขหรือตรรกะ

ตัวอย่างคำส่ง while loop 

i = 1
while i < 10:
  print(i)
  i += 1

ผลที่ได้จากการสั่งให้โปรแกรมทำงาน

1
2
3
4
5
6
7
8
9

อธิบายคำสั่งจากโค้ดตัวอย่างด้านบน คือ

  1. กำนดตัวแปร i เท่ากับ 1
  2. เปรียบเทียบใน while  หาก i มีค่าน้อยกว่า 10 จริงจะทำในคำสั่งต่อมา
  3. จะแสดงค่า i ออกมา
  4. เพิ่มค่า i ไป 1
  5. จากนำก็นำค่า i ไปเปรียบเทียบ ใน while ต่อ
  6. ทำวนไปเรื่อย ๆ จนกว่าจะมีค่าความจริงเป็นเท็จจึงจะออกจาก loop

ตัวอย่างคำสั่งที่ 2 คำสั่ง while loop

 

i = 20
while i > 1:
  print(i)
  i -= 1

ผลที่ได้จากการทำงานโปรแกรม

10
9
8
7
6
5
4
3
2

slot gacor hari ini slot qris slot gacor maxwin slot online slot gacor gampang menang slot gacor hari ini slot online slot slot slot guci777 guci777 fafatogel fafatogel fafatogel fafatogel agen138 slot agen138 slot data hk bola slot bolaslot99 bola slot agen138 link alternatif koin138 link alternatif agen138 slot ag138 slot slot gacor slot thailand