[英]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_book
和query 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.