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()
CodePudding user response:
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")
CodePudding user response:
You should just check for the len and if ChosenPokInt is in it's boundaries:
pokemon_index = ChosenPokInt - 1
if 0 <= pokemon_index < len(Starter)-1:
# everything is fine
else:
# handle the problem case
Besides that I advice you to look into pep8 :). You can find an awesome guide here: https://pep8.org
CodePudding user response:
You can add a while loop before the condition that checks first if the input is in the correct range:
ChosenPok = ChoseStarter()
pokRange = [1, 2, 3]
while not (ChosenPok in pokRange):
print("Wrong input, try again")
ChosenPok = ChoseStarter()