简体   繁体   中英

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:

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.

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:

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:

    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. Some time that also gives error so use Try-Except method to break the loop anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM