简体   繁体   English

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

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

I'm trying to make a small game using Python3.我正在尝试使用 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:上述游戏中有 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

For reference heres the code i've been trying:作为参考,这是我一直在尝试的代码:

 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

edit: Looked like some people were trying to point me towards another question (How to check if string input is a number) .编辑:看起来有些人试图将我指向另一个问题(如何检查字符串输入是否为数字) I went to this before posting the question and couldn't find anything helping out so i went to write this.在发布问题之前我去了这个,找不到任何帮助,所以我去写这个。 Thank you though to everyone who tried to help, It is working now:)感谢所有试图提供帮助的人,它现在正在工作:)

Removing the int() from your input statement should work.从输入语句中删除 int() 应该可以。 It might be easier to make the random number a string so you don't have issues with the different data types.将随机数设为字符串可能更容易,这样您就不会遇到不同数据类型的问题。

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

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

This happens because python is trying to transform a character to an integer, you already account for that case in the last elif.发生这种情况是因为 python 试图将字符转换为 integer,您已经在最后一个 elif 中考虑了这种情况。 Any other answer that is not an integer from 1 to 3 will raise the Error print statement任何其他不是从 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

The Pythonic way to deal with this is called EAFP : Easier to ask for forgiveness than permission.处理这个问题的 Pythonic 方法称为EAFP :请求宽恕比请求许可更容易。 Wrap the code with try and except statements so you can detect when something invalid is entered.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

If that doesn't suit your style, it's easy to check a string to ensure it can be converted to an integer before you do it:如果这不适合您的风格,那么在执行此操作之前,可以轻松检查字符串以确保可以将其转换为 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.

相关问题 Python:如何在文本文件中搜索用户输入的包含整数的字符串? - Python: How can I search a text file for a string input by the user that contains an integer? 在用户使用 While 循环在 Python 上输入整数和非 0 值之前,如何不断提示用户输入? - How can I keep prompting the user for input until the user enters an integer and non-0 value on Python using While loop? 如何在python中用字符串附加用户输入(整数)? - How do I append the user input (integer) with a string in python? 如何将用户整数输入与字典中的值进行比较? (Python) - How do I compare user integer input to values in dictionary? (Python) 如何检测用户何时击中enter作为input() - How do I detect when a user hits enter as input() 如何确保我的代码继续循环,同时只接受来自用户输入的整数值? - How can I make sure my code continues to loop while only accepting integer values from the user input? 如何在整数输入的基础上重复句子? - How can I repeat the sentence on the basis of integer input? 如何检查输入是否为数字,然后将其转换为 integer? - How can I check if an input is a number and then turn it into an integer? 如何同时要求浮点输入和整数? - How can I ask for a float input and an integer at the same time? 如何检测键盘输入以使用python播放声音? - How can I detect keyboard input to play a sound with python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM