Search code examples
pythonloopsinputwhile-loopcontinue

Recall `input` with a while loop if an incorrect answer is supplied


Python doesn't return to the enclosing loop when I use continue, due to a mistake I can't catch.

The following loop should prompt the user for two generic names I set up: George and David. I want to have it set up so Anaconda asks the user for their name. If they enter George, it says Hi George. If they enter David, it says Hi David.

If the user enters any other name, it calls back the loop to try again. I am still a beginner at Python and my knowledge of control flow here shows.

I know that continue works only with a while conditional. My code was written such that: else, while the name is not George or David, trigger continue, which should go to the enclosing loop (if the name is not David or George, ask for the name again).

name = ''
if name != 'David' and name != 'George':
    print('What is your name?')
    name  = input()
    if name == 'David':
        print('Hi David')
    elif name == 'George':
        print('Hi George')
    else:
        while name != 'George' or 'David' :
            continue

Solution

  • You have while and if mixed up. There are actually multiple ways to solve this:

    name = ''
    while True:
        print('What is your name?')
        name = input()
        if name == 'David':
            print('Hi David')
            break
        if name == 'George':
            print('Hi George')
            break
    

    Or

    name = ''
    while name != 'David' and name != 'George':
        print('What is your name?')
        name = input()
    if name == 'David':
        print('Hi David')
    elif name == 'George':
        print('Hi George')
    

    Or even better, you could use in to check if name is an element in the set of all accepted names. For the print call, you don't have to explicitly write David and George again, but you can use the new variable name:

    name = ''
    while name not in {'David', 'George'}:
        print('What is your name?')
        name = input()
    print('Hi {}'.format(name))