Python输入永远不等于整数
我想插入一个数字,如果我输入除4以外的任何数字,它会告诉我这是错误的,但如果它是错误的,它会告诉我“gg你赢了,noob.”。然而,当我插入4时,它告诉我它是不正确的Python输入永远不等于整数,python,Python,我想插入一个数字,如果我输入除4以外的任何数字,它会告诉我这是错误的,但如果它是错误的,它会告诉我“gg你赢了,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 3+中,inpu
x = input("Insert a numer: ")
while x != 4:
print("incorrect")
x =input("Insert another number: ")
if x == 4:
print("gg you win, noob")
在Python 3+中,
input
返回一个字符串,4
不等于'4'
。您必须修改为:
while x != '4':
或者使用
int
,如果输入不是int,请仔细检查ValueError
。在Python 3+中,input
返回字符串,4
不等于'4'
。您必须修改为:
while x != '4':
或者也可以使用
int
,如果输入不是int,请仔细检查是否存在ValueError
。来自input()
的结果将是一个字符串,在比较之前需要将其转换为整数:
x = int(input("Insert another number: ")
如果您的输入不是一个数字,这将引发一个
ValueError
。来自input()
的结果将是一个字符串,您需要在比较它之前将其转换为整数:
x = int(input("Insert another number: ")
如果您的输入不是一个数字,这将引发一个
ValueError
。这里,如果x==4,则不需要。因为直到x
等于4
时,while
循环将不会被传递。您可以这样尝试:
x = int(input("Insert a numer: "))
while x != 4:
print("incorrect")
x = int(input("Insert another number: "))
print("gg you win, noob")
这里,如果x==4,则不需要。因为直到x
等于4
时,while
循环将不会被传递。您可以这样尝试:
x = int(input("Insert a numer: "))
while x != 4:
print("incorrect")
x = int(input("Insert another number: "))
print("gg you win, noob")
Python 2和3在函数input()
上有所不同
- 在Python 2中,
input()
相当于eval(原始输入())
- 在Python3中,没有
raw\u input()
,但是input()
与Python2的raw\u input()
类似
就你而言:
- 在Python2中,
input()
为您提供类型为int
的4
,因此您的程序可以运行
- 在Python3中,
input()
为您提供了类型为str
的'4'
,因此您的程序有缺陷
在Python3中,解决此问题的一种方法是使用eval(input())
。但是在不受信任的字符串上使用eval
是非常危险的(是的,您的程序在Python2中工作非常危险)。因此,您应该首先验证输入。Python2和Python3在函数input()
中有所不同
- 在Python 2中,
input()
相当于eval(原始输入())
- 在Python3中,没有
raw\u input()
,但是input()
与Python2的raw\u input()
类似
就你而言:
- 在Python2中,
input()
为您提供类型为int
的4
,因此您的程序可以运行
- 在Python3中,
input()
为您提供了类型为str
的'4'
,因此您的程序有缺陷
在Python3中,解决此问题的一种方法是使用eval(input())
。但是在不受信任的字符串上使用eval
是非常危险的(是的,您的程序在Python2中工作非常危险)。因此,您应该首先验证输入。尝试以下方法:
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
循环将从头开始重复您的脚本,而不会引发错误。尝试以下操作:
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
循环将从头开始重复您的脚本,而不会引发错误。Python 2或Python 3?他所说的公平假设3,因为这在2中有效。@brianpck这是一个公平的假设,但我不会说它在2中完全“有效”。无论哪种方式,代码都是错误的,但问题不同。@brianpck是的。这是python 3Python 2或python 3?他说的是3,这是一个公平的假设,因为它在2中起作用。@brianpck这是一个公平的假设,但我不会说它在2中完全“起作用”。无论哪种方式,代码都是错误的,但问题不同。@brianpck是的。这是python 3Python 2 vs 3:python 2 vs 3: