2021年5月4日星期二

How can i detect if the user input is not an integer?

I'm trying to make a small game using Python3. There are 3 options in the said game giving the user the option to input '1' '2' or '3', right now if anything other than an integer is inputted it crashes with the message:

Traceback (most recent call last):    File "main.py", line 62, in <module>      user_choice = int(input("""  ValueError: invalid literal for int() with base 10: 'fj        while i < round_select: #Loops for value of round_select    i += 1 #adds value to round_select every round until user input met      opponent = random.randint(1,3)   #generates random integer printed as paper, scissors, or rock by above function              time.sleep (0.2)        user_choice = int(input("""        (1)Paper, (2)Scissors, (3)Rock!: """))          if user_choice == opponent:          print (username + choice_to_text(user_choice))           print ("Opponent" + choice_to_text(opponent))           print ("Tie")          ties += 1         elif (user_choice == 1 and opponent == 2)  or (user_choice == 2 and opponent == 3) or (user_choice == 3 and opponent == 1): #outcomes grouped together to avoid mountains of elif statements          print (username +  choice_to_text(user_choice))          print ("Opponent"  + choice_to_text(opponent))          print ("One point to the opponent!")          opponent_score += 1        elif (user_choice == 1 and opponent == 3) or (user_choice == 2 and opponent == 1) or (user_choice == 3 and opponent == 2):          print (username + choice_to_text(user_choice))          print ("Opponent" + choice_to_text(opponent))          print ("One point to " + (username) + "!")          user_score += 1        elif user_choice != int or user_choice == ValueError:          print ("Please type an integer between 1 and 3 ")          i -= 1  
https://stackoverflow.com/questions/67394554/how-can-i-detect-if-the-user-input-is-not-an-integer May 05, 2021 at 10:49AM

没有评论:

发表评论