繁体   English   中英

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

[英]How can I detect if the user input is not an integer?

我正在尝试使用 Python3 制作一个小游戏。 上述游戏中有 3 个选项让用户可以选择输入“1”“2”或“3”,现在如果输入 integer 以外的任何内容,它会崩溃并显示以下消息:

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

编辑:看起来有些人试图将我指向另一个问题(如何检查字符串输入是否为数字) 在发布问题之前我去了这个,找不到任何帮助,所以我去写这个。 感谢所有试图提供帮助的人,它现在正在工作:)

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

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

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

发生这种情况是因为 python 试图将字符转换为 integer,您已经在最后一个 elif 中考虑了这种情况。 任何其他不是从 1 到 3 的 integer 的答案都会引发错误打印语句

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

处理这个问题的 Pythonic 方法称为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

如果这不适合您的风格,那么在执行此操作之前,可以轻松检查字符串以确保可以将其转换为 integer:

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.")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM