-1

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)

3 Answers3

1

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)
Pranav Hosangadi
  • 17,542
  • 5
  • 40
  • 65
wordinone
  • 139
  • 1
  • 9
1

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)
Samwise
  • 51,883
  • 3
  • 26
  • 36
-1
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)
BeRT2me
  • 2,930
  • 1
  • 4
  • 24