如何检测用户输入是否不是整数?

2024-10-02 00:40:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python3制作一个小游戏。上述游戏中有3个选项,用户可以选择输入“1”、“2”或“3”,此时,如果输入的不是整数,则会与消息一起崩溃:

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

编辑: 看起来好像有人想把我引向另一个问题。我在发帖前看了这篇文章,没有找到任何帮助,所以我写了这篇文章。 不过,感谢所有试图提供帮助的人,它现在起作用了:)


Tags: orandtotextinputusernameselectint
2条回答

处理这个问题的python方法叫做EAFP:请求原谅比允许更容易。用tryexcept语句包装代码,以便在输入无效内容时进行检测

try:
  user_choice = int(input("""
  (1)Paper, (2)Scissors, (3)Rock!: """))
except ValueError:
  # do something here like display an error message and set a flag to loop for input again

如果这不适合您的风格,那么在执行此操作之前,很容易检查字符串以确保它可以转换为整数:

bad_input = True
while bad_input:
  user_choice = input("""
  (1)Paper, (2)Scissors, (3)Rock!: """)
  if user_choice.isnumeric():
    user_choice = int(user_choice)
    if user_choice in (1, 2, 3):
      bad_input = False
    else:
      print("Bad input, try again.")

从输入语句中删除int()应该可以。将随机数设置为字符串可能更容易,这样就不会出现不同数据类型的问题

user_choice = input("""(1)Paper, (2)Scissors, (3)Rock!: """)

opponent = str(random.randint(1,3))

之所以会发生这种情况,是因为python试图将字符转换为整数,您已经在上一个elif中说明了这种情况。任何不是1到3之间的整数的其他答案都将引发错误打印语句

while i < round_select: #Loops for value of round_select
    i += 1 #adds value to round_select every round until user input met
    
    opponent = str(random.randint(1,3))   #generates random integer printed as paper, scissors, or rock by above function
    
    time.sleep (0.2)
    user_choice = 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

相关问题 更多 >

    热门问题