How to create a loop for this code? (Python)

Question:

I have a dictionary of names (Dan, Bianca, and Bob)

If the name is NOT found , I want to loop and ask for the name again.

How do I create a loop for this code??

name = input('Enter your name: ')   

options = {'Dan': 1, 'Bianca': 2, 'Bob': 3}

key = name

print('Searching for ' + name + ' in the list...')

if key in options:
    print(name + ' was found on the list')
    found = True
    print(found)
else:
    print(name + ' was NOT found')
    found = False
    print(found)

Answers:

options = {'Dan': 1, 'Bianca': 2, 'Bob': 3}

while True:
    name = input('Enter your name: ')   

    key = name

    print('Searching for ' + name + ' in the list...')

    if key in options:
        print(name + ' was found on the list')
        found = True
        print(found)
        break  # <-- Breaks out of the while loop if name was found.
    else:
        print(name + ' was NOT found')
        found = False
        print(found)
Answered By: BeRT2me

If you want to stop the loop if there is a matching name in the list, you can do it as follows

def check_names(name, options):
    print('Searching for ' + name + ' in the list...')

    if name in options:
        print(name + ' was found on the list')
        found = True
        return found
    else:
        print(name + ' was NOT found')
        found = False
        return found

found = False
while found == False:
    name = input('Enter your name: ')   
    options = {'Dan': 1, 'Bianca': 2, 'Bob': 3}
    found = check_names(name, options)
    print(found)
Answered By: wordinone

Prompt for input in a while True: loop and break when name in options:

options = {'Dan': 1, 'Bianca': 2, 'Bob': 3}
while True:
    name = input('Enter your name: ')
    if name in options:
        break
    print(f'{name} was NOT found')
    print(False)

print(f'{name} was found in the list')
print(True)
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.