Search code examples
pythonadventure

Can't finish the loop when asking for valid answers


I have a problem with my code that I can't find the solution as well. I ask for questions that has to be valid but the loops just continues, and let me input.

print('Do you want to go to the store or woods?')

lists = ('woods', 'store')
while True:
    answers = input()    
    if answers == 'store':
        break
        print('Going to the store...')
    elif answers == 'woods':
        break
        print('Going to the woods...')
    while lists not in answers:
        print('That is not a valid answer')

Solution

  • First of all, your print statements are unreachable. You can find more information here.

    #...
    if answers == 'store':
            print('Going to the store...')
            break
        elif answers == 'woods':
            print('Going to the woods...')
            break
    #...
    

    Then, your second while statement makes no sense in this way. If you just wanted to print That is not a valid answer in case the input differs from store or woods and give a user another try - then you can just use else, without lists at all:

    print('Do you want to go to the store or woods?')
    
    # no lists
    while True:
        answers = input()
        if answers == 'store':
            print('Going to the store...')
            break
        elif answers == 'woods':
            print('Going to the woods...')
            break
        else:
            print('That is not a valid answer')
    

    If you instead would like to check, whether the user's input is encountered in lists, then you need to do this in trick inside out:

    print('Do you want to go to the store or woods?')
    
    lists = ('woods', 'store')
    while True:
        answers = input()
        if answers == 'store':
            print('Going to the store...')
            break
        elif answers == 'woods':
            print('Going to the woods...')
            break
        elif answers not in lists:
            print('That is not a valid answer')
        else:
            # some default case, for example sys.exit() (needs sys to be imported)