在不知道要重複幾次的時候,用 while 迴圈——只要條件成立就一直跑,直到條件不成立才停。下面兩個例子:一個用計數器跑 5 次,一個用 input() 一直問到輸入 q 才停。
Example 1:計數器 — 跑 5 次 #
count = 1
while count <= 5:
print("Count is:", count)
count += 1output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
Example 2:一直問到輸入 q — break 跳出 #
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == "q":
print("Bye!")
breakoutput:
Enter 'q' to quit: hello Enter 'q' to quit: world Enter 'q' to quit: q Bye!
