簡體   English   中英

如果循環中未提供輸入(或按下回車鍵),如何在 python 中結束無限循環

[英]How do I end an infinite loop in python if no input(or the enter key is pressed) is provided in the loop

這是我的代碼

while True:
    query = str(input()) 

    if query in phone_book: #phone_book is a dictionary here
        print(phone_book.get(query))
    elif query not in phone_book:
        print('Not found')
    elif query == (''): #I tried using none instead of empty string but it kept running the loop
        break

使用not語句:

if query in phone_book: #phone_book is a dictionary here
    print(phone_book.get(query))
elif query not in phone_book:
    print('Not found')
elif not query:
    break

您的條件順序錯誤。

您的前兩個條件是query in phone_bookquery not in phone_book中的查詢彼此相反,因此其中一個將評估True ,並且永遠不會到達elif query == ('')行。

嘗試這個:

while True:
    query = str(input()) 
    if query == '':
        break
    elif query in phone_book: #phone_book is a dictionary here
        print(phone_book.get(query))
    elif query not in phone_book:
        print('Not found')

或者只是最后一個使用else

while True:
    query = str(input()) 
    if query == '':
        break
    elif query in phone_book: #phone_book is a dictionary here
        print(phone_book.get(query))
    else:
        print('Not found')

嘗試使用 Try 和 except 方法來打破循環:

    while(True):
        try:
            query = input()
            if query in phoneBook:
                print(f"{query}={phoneBook.get(query)}")
            elif  query not in phoneBook:
                if (query ==''):
                    break
                else:
                    print("Not found")
        except:
            break

在這里,當您在代碼中沒有提供任何輸入時,計算機會將其作為空格並打印“未找到”,因此當輸入與字典內容不匹配時,我們需要檢查輸入是否無效輸入或沒有輸入的“ENTER”以打破循環。 有時也會出錯,所以無論如何都要使用 Try-Except 方法來打破循環。

暫無
暫無

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

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