繁体   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