Search code examples
pythonif-statementwhile-loop

My goal here is to have the user choose between 3 options and if they don't it shows an error message and keeps them in the loop


The top 3 lines just generates 3 random pokemon names. The issue comes in the "If" statement as when the user inputs something that is not an option, it passes the if statement, but because it wasn't an option, the user is still stuck in the while loop.

def pkmn_choice1():
    Pokemon1 = Pokemon_dct[f'{random_pkmn1}'].pokechoice()
    Pokemon2 = Pokemon_dct[f'{random_pkmn2}'].pokechoice()
    Pokemon3 = Pokemon_dct[f'{random_pkmn3}'].pokechoice()
    choices1 = [f'{Pokemon1}', f'{Pokemon2}', f'{Pokemon3}']
    print("Choose one of these Pokemon to fight with.")
    userinput1 = ""
    while userinput1 not in choices1:
        print(f"Options: {Pokemon1}, {Pokemon2}, or {Pokemon3}.")
        userinput1 = input()
        if userinput1 == f"{Pokemon1}" or f"{Pokemon2}" or f"{Pokemon3}":
            print(f'You have chosen {userinput1} to be your partner.')
            Pokemon_dct[f'{userinput1}'].pokeinfo1()
        else:
            print("That was not a valid selection. Please try again")

Solution

  • This is not how you build proper comparison against multiple values. Instead of:

    if userinput1 == f"{Pokemon1}" or f"{Pokemon2}" or f"{Pokemon3}":
    

    you need to write

    if userinput1 == f"{Pokemon1}" or userinput1 == f"{Pokemon2}" or userinput1 == f"{Pokemon3}":
    

    but that gets lengthy so go smarter and write

    if userinput1 in [f"{Pokemon1}", f"{Pokemon2}", f"{Pokemon3}"]: