Python 循环,直到输入为特定类型
我试图制作一个程序,反复向用户请求输入,直到输入为特定类型。我的代码:Python 循环,直到输入为特定类型,python,python-3.x,Python,Python 3.x,我试图制作一个程序,反复向用户请求输入,直到输入为特定类型。我的代码: value = input("Please enter the value") while isinstance(value, int) == False: print ("Invalid value.") value = input("Please enter the value") if isinstance(value, int) == True: break 根据我
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
根据我对python的理解,行
if isintance(value, int) == True
break
如果值是整数,则应结束while循环,但它不是整数
我的问题是:a) 如何生成一个代码,请求用户输入,直到输入为整数
b) 为什么我的代码不工作?代码不工作的原因是
input()
将始终返回字符串。这将始终导致isinstance(value,int)
的计算结果始终为False
您可能想要:
value = ''
while not value.strip().isdigit():
value = input("Please enter the value")
input
始终返回字符串,您必须自己将其转换为int
请尝试以下代码段:
while True:
try:
value = int(input("Please enter the value: "))
except ValueError:
print ("Invalid value.")
else:
break
请注意,使用
.isdigit()
时,它将在负整数上返回False。因此,isinstance(value,int)
可能是一个更好的选择
由于代表性低,我无法对接受的答案发表评论。如果要管理负整数,应使用:
value = ''
while not value.strip().lstrip("-").isdigit():
value = input("Please enter the value")
input
始终返回字符串对象(str
)。可能需要值。isdigit()和==False
永远不正常:-)。总是而不是什么!输入返回int(如果给定)。尝试输入()+1并将2作为输入/在Python3中,input()
返回字符串。在Py2中,input()
与Py3中的eval(input())
相同,所以您可能需要value.strip().isdigit()
Hmm,我不知道。谢谢