共計 494 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 的 while 循環可以有多種終止方式,下面列舉了一些常用的方法:
- 使用條件判斷:在循環體內部設置一個條件判斷語句,當條件不滿足時,循環終止。
count = 0
while count < 10:
print(count)
count += 1
- 使用 break 語句:在循環體內部使用 break 語句來終止循環。
count = 0
while True:
if count >= 10:
break
print(count)
count += 1
- 使用標志變量:在循環體外部定義一個標志變量,當標志變量滿足某個條件時,終止循環。
flag = True
count = 0
while flag:
if count >= 10:
flag = False
print(count)
count += 1
- 使用異常處理:使用 try-except 語句捕獲特定的異常來終止循環。
count = 0
while True:
try:
if count >= 10:
raise StopIteration
print(count)
count += 1
except StopIteration:
break
以上是一些常用的終止 while 循環的方法,具體選擇哪種方法取決于每個具體情況。
丸趣 TV 網 – 提供最優質的資源集合!
正文完