簡體   English   中英

用戶輸入后重復for循環?

[英]Repeat a for loop after user input?

讓我用一個例子來解釋我的問題。

這里我有一個簡單的 for 循環:

for x in range(10)
    print(x)

output: 0 1 2 3 4 5 6 7 8 9

現在,如果我從 flask 網站或麥克風中獲取用戶輸入,讓人們說是或否,那么我希望它再次啟動 for 循環或根據響應跳出 for 循環。 如果該人說是,則再次重做 for 循環,或者如果該人說沒有,則退出 for 循環並繼續執行其他代碼。

問題:

如何在用戶輸入后重復 for 循環。

我在問如何使用 for 循環而不是 while 循環來執行此操作,因為我想將它放在執行其他操作的 while 循環中。

您尚未指定如何檢索輸入,因此我在以下代碼片段中省略了該內容:

should_run_loop = True

while should_run_loop:
    for x in range(10)
        print(x)
    should_run_loop = # code to retrieve input

將您的循環放入另一個循環中:

while True:
    for x in range(10):
        print(x)
    if not input("Do it again? ").lower().startswith("y"):
        break

如果嵌套循環的數量開始變得難以處理,請將其中的一些放在 function 中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM