ลูป while
ทำซ้ำwhileเงื่อนไขเป็นจริง
- ลูป
whileจะทำซ้ำ ตราบใดที่ เงื่อนไขของมันยังเป็นจริง - มันจะตรวจสอบเงื่อนไข ก่อน แต่ละรอบ
- ใช้เมื่อไม่ทราบจำนวนรอบการทำซ้ำล่วงหน้า
ต้องเปลี่ยนเงื่อนไขเสมอ
- สิ่งบางอย่างภายในลูปต้องเคลื่อนที่ไปสู่การทำให้เงื่อนไขเป็นfalse
- หากมันไม่เป็นfalseตลอดไป ลูปจะรันไปเรื่อยๆ (เป็น infinite loop)
- กด Stop ถ้าลูปติดขัด
count = 3
while count > 0:
print(count)
count = count - 1
break และ continue
breakจะหยุดลูปทันทีcontinueจะข้ามส่วนที่เหลือของรอบนี้และไปยังรอบถัดไปwhile True:จะวนลูปไปเรื่อยๆ จนกว่าจะเจอbreakที่หยุดมัน
n = 0
while True:
n = n + 1
if n == 4:
break
print(n)
ตรวจสอบก่อนหรือหลัง
- ลูป
whileจะตรวจสอบ ก่อน ดังนั้นอาจรัน ศูนย์ ครั้ง - ลูป "repeat until" จะตรวจสอบ หลัง ดังนั้นจะรัน อย่างน้อย หนึ่งครั้ง
- Python ไม่มี
repeat; ใช้while True:พร้อมbreakที่ท้าย
In Cambridge pseudocode
whileคือ pre-condition loop;REPEAT … UNTILคือ post-condition loop
Count ← 3
WHILE Count > 0
OUTPUT Count
Count ← Count - 1
ENDWHILE
REPEAT
OUTPUT Count
Count ← Count + 1
UNTIL Count = 3
ข้อผิดพลาดที่พบบ่อย
- เปลี่ยนสิ่งบางอย่างภายในลูปเพื่อให้เงื่อนไขกลายเป็นfalseได้ มิฉะนั้นจะรันไปเรื่อยๆ
- A
whileตรวจสอบเงื่อนไขก่อน ดังนั้นอาจรันศูนย์ครั้ง
ลองดูเลย
- ตรวจสอบให้แน่ใจว่าเงื่อนไขของคุณจะกลายเป็นfalseในที่สุด
- ติดกับลูป? ทำ drill สั้น Finish the countdown ก่อน มันคือบรรทัดที่ขาดหายไปหนึ่งบรรทัด
- กด Check answer เพื่อทดสอบโค้ดของคุณ
A while loop builds up a value
A while loop repeats until its condition is false.
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Use a while loop to count down. Each turn, print the value of count, then make count one smaller. Stop when it reaches 0, so the output is 5, 4, 3, 2, 1 — one per line.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Use a while loop to add up the numbers 1 ไป 10. Store the total in total (the answer is 55).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
เริ่ม n at 1 and add 1 each pass. The loop stops too soon: it ends while n is still 1. Change the condition so it keeps going while n * n is at most 50. When it stops, n is the first whole number whose square is over 50.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Same answer, with break. n starts at 1 inside while True:. The if is already inside the loop and n grows หลังจาก it. Change the condition so you break when n * n is greater than 50. Leave the answer in n (it is 8). Do not add 1 before the test — that makes the answer 9.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Start with n = 1 และ steps = 0. While n is smaller than 1000, double n and add 1 ไป steps. When the loop ends, n เป็น 1024. How many doublings did it take? Leave the answer in steps.
คลิก Run เพื่อดูผลลัพธ์ที่นี่