讓我用一個例子來解釋我的問題。
這里我有一個簡單的 for 回圈:
for x in range(10)
print(x)
輸出: 0 1 2 3 4 5 6 7 8 9
現在,如果我從 Flask 網站或麥克風中獲取用戶輸入,讓人們說是或否,那么我希望它重新開始 for 回圈或根據回應跳出 for 回圈。如果此人說是,則再次重做 for 回圈,或者如果此人說沒有中斷 for 回圈并繼續執行其他代碼。
問題:
如何在用戶輸入后重復 for 回圈。
我在問如何用 for 回圈而不是 while 回圈來做到這一點,因為我想把它放在一個做其他事情的 while 回圈中。
uj5u.com熱心網友回復:
將您的回圈放入另一個回圈中:
while True:
for x in range(10):
print(x)
if not input("Do it again? ").lower().startswith("y"):
break
如果嵌套回圈的數量開始變得笨拙(任何超過大約三個級別的深度開始變得難以閱讀 IMO),請將其中的一些邏輯放入函式中:
def count_to_ten():
for x in range(10):
print(x)
while True:
count_to_ten()
if not input("Do it again? ").lower().startswith("y"):
break
uj5u.com熱心網友回復:
您尚未指定如何檢索輸入,因此我在以下代碼片段中省略了該內容:
should_run_loop = True
while should_run_loop:
for x in range(10)
print(x)
should_run_loop = # code to retrieve input
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401846.html
