[英]How do I end an infinite loop in python if no input(or the enter key is pressed) is provided in the loop
This is my code这是我的代码
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
Use a not
statement:使用
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
You have your conditions in the wrong order.您的条件顺序错误。
Your first two conditions are query in phone_book
and query not in phone_book
are the inverse of each other, so one of them will evaluate True
, and the elif query == ('')
line is never reached.您的前两个条件是
query in phone_book
和query not in phone_book
中的查询彼此相反,因此其中一个将评估True
,并且永远不会到达elif query == ('')
行。
Try this:尝试这个:
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')
or alternatively just an use else
for the last one:或者只是最后一个使用
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 to Use Try and Except method to break the Loop:尝试使用 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
Here, when you don't give any input in the code than Computer take that as a Space and so prints "Not Found", so when input doesn't matches with dictionary content, then we need to check if the input is an invalid input or an "ENTER" without input to break the loop.在这里,当您在代码中没有提供任何输入时,计算机会将其作为空格并打印“未找到”,因此当输入与字典内容不匹配时,我们需要检查输入是否无效输入或没有输入的“ENTER”以打破循环。 Some time that also gives error so use Try-Except method to break the loop anyway.
有时也会出错,所以无论如何都要使用 Try-Except 方法来打破循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.