2013-10-23 27 views
0

我正在试图制作一个程序,该程序反复询问用户输入,直到输入为特定类型。我的代码:根据我的Python的理解,行循环直到输入是特定类型

if isintance(value, int) == True 
    break 

应该结束while循环,如果是一个整数

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 

,但事实并非如此。

我的问题是:
a)如何编写一个代码,要求用户输入,直到输入为整数?
b)为什么我的代码不工作?

+2

'input'总是返回字符串对象('str')。 – falsetru

+1

可能想要value.isdigit() – Hoopdady

+0

和' == False'永远不会:-)。总是只是'不是' – Hoopdady

回答

2

您的代码不起作用的原因是因为input()将始终返回一个字符串。这总是会导致isinstance(value, int)始终评估为False

你可能想:

value = '' 
while not value.strip().isdigit(): 
    value = input("Please enter the value") 
+1

另外,你可能需要'value.strip()。isdigit() ' – JadedTuna

+0

当然,好点。 – Hoopdady

+0

嗯,不知道。谢谢! –

0

input总是返回一个字符串,你必须把它自己转换为int

试试这个片断:

while True: 
    try: 
     value = int(input("Please enter the value: ")) 
    except ValueError: 
     print ("Invalid value.") 
    else: 
     break 
0

使用.isdigit()时,请注意,它会返回负整数假。所以isinstance(value, int)也许是更好的选择。

我不能评论接受的答案,因为低代表。

0

如果你要管理你应该使用负整数:

value = '' 
while not value.strip().lstrip("-").isdigit(): 
    value = input("Please enter the value")