Skip to content
Advertisement

How to avoid my program stopping because of a invalid index number when calling a tuple

I’m trying to make a pokémon text based journey in python. I listed the starter pokémon in a tuple to call the number that the user typed in the input to then store the chosen starter pokémon.

It all works but when the user would type a different integer then availabe in the tuple, for example: writing 5 while there are only 3 indexs in the tuple. The program just stops when this happens.

Is there a way for me to just tell the program to not go into debugging mode when this happens; and recalling the “ChoseStarter” function instead?

Here is the code:

if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3):

    ChosenPokInt = int(ChosenPok)
    StarterPok = Starter[ChosenPokInt-1] #Here is the problem

    Sure = f"You chose {StarterPok} are you sure? (y/n)"
    YORN = input(Sure)
    if(YORN == "Y" or YORN == "y"):
        Congrats = f"Congratulations!! You just got a {StarterPok}!!"
        WriteFast(Congrats)
        print(Starter[ChosenPokInt-1])
    else:
        WriteFast(ERROR)
        ChoseStarter()

Advertisement

Answer

No idea what the question is about or what logic you want to implement. See if the below code helps though. Seems like the “if condition” is buggy in your case. The following code repeatedly asks for the correct input using a while loop. Replace the while loop with an if statement if you don’t want that.

starter = ["x", "y", "z"]
chosen_pok = int(input("Select a pok: "))

while not (1 < chosen_pok < 4):
  print("Invalid pok. try again...")
  chosen_pok = int(input("Select a pok: "))

starter_pok = starter[chosen_pok - 1]
yorn = input(f"You chose {starter_pok} are you sure? (y/n)")

if (yorn in ["Y", "y"]):
  print(starter[chosen_pok - 1])
else:
  print("Error")
Advertisement