【问题标题】:Python input never equals an integerPython 输入从不等于整数
【发布时间】:2016-09-29 16:14:19
【问题描述】:

我想插入一个数字,如果我输入 4 以外的任何数字,它会告诉我这是错误的,但如果它是错误的,它会告诉我“gg you win, noob.”。但是当我插入 4 时,它告诉我它不正确。

x = input("Insert a numer: ")

while x != 4:
   print("incorrect")
    x =input("Insert another number: ")

if x == 4:
    print("gg you win, noob")

【问题讨论】:

  • Python 2 还是 Python 3 ?
  • 公平假设他说的是 3,因为这适用于 2。
  • @brianpck 这是一个合理的假设,但我不会在 2 中准确地说 "works"。无论哪种方式,代码都是错误的,但存在不同的问题。
  • @brianpck 是的。这是python 3

标签: python


【解决方案1】:

在 Python 3+ 中,input 返回一个字符串,4 不等于 '4'。您必须修改:

while x != '4':

或者使用int,如果输入不是int,请小心检查ValueError

【讨论】:

【解决方案2】:

input() 的结果将是一个字符串,您需要在比较之前将其转换为整数:

x = int(input("Insert another number: ")

如果您输入的不是数字,这将引发ValueError

【讨论】:

    【解决方案3】:

    在这里,if x == 4 不是必需的。因为直到x 等于4while 循环才会通过。你可以这样试试:

    x = int(input("Insert a numer: "))
    while x != 4:
        print("incorrect")
        x = int(input("Insert another number: "))
    
    print("gg you win, noob")
    

    【讨论】:

      【解决方案4】:

      Python 2 和 3 在函数 input() 上有所不同。

      • 在 Python 2 中,input() 等价于 eval(raw_input())
      • 在 Python 3 中,没有 raw_input(),但 input() 的工作方式类似于 Python 2 的raw_input()

      在你的情况下:

      • 在 Python 2 中,input() 为您提供 4 类型为 int,因此您的程序可以正常工作。
      • 在 Python 3 中,input() 为您提供 '4' 类型为 str,因此您的程序有问题。

      在 Python 3 中,解决此问题的一种方法是使用 eval(input())。但是在不受信任的字符串上使用eval 是非常危险的(是的,您的程序在 Python 2 中运行很危险)。所以你应该先验证输入。

      【讨论】:

        【解决方案5】:

        试试这个:

            z = 0
        while z != "gg you win, noob":
            try:
               x = int(input("Insert a numer: "))
               while x != 4:
                   print("incorrect")
                   x =int(input("Insert another number: "))
        
               if x == 4:
                    z = "gg you win, noob"
                    print(z)
        
            except:
                print('Only input numbers')
        

        这会将您的所有输入值转换为整数。如果您不输入整数,except 语句将提示您只输入数字,while True 循环将从头开始重复您的脚本,而不是引发错误。

        【讨论】:

          猜你喜欢
          • 2021-05-01
          • 1970-01-01
          • 2015-08-06
          • 1970-01-01
          • 2015-09-08
          • 1970-01-01
          • 2020-04-15
          • 2011-08-09
          • 2014-03-28
          相关资源
          最近更新 更多