while循环在Python中识别整数

时间:2015-10-25 22:44:22

标签: python for-loop while-loop numbers

我正在尝试编写一个程序来计算密度,我尝试创建一个while循环,以防止用户输入任何内容或非卷数。

但是当我运行程序时,它只是循环“你必须永远键入一个值”。我在for循环中尝试了相同的代码,输入2个数字后它确实有效。

def GetVolume():
    print("How many cublic cm of water does the item displace")
    Volume = input()
    while Volume == ("") or type(Volume) != int:
        print("You have to type a value")
        Volume = input()
    return float(Volume)

3 个答案:

答案 0 :(得分:1)

假设您使用的是Python 3,则会编写此解决方案。您的代码中的问题是您假设如果键入数字,input方法将返回type int。这是不正确的。您将始终从输入中获取字符串。

此外,如果您尝试在输入周围强制转换int以强制执行int,则输入字符串时代码将会增加:

ValueError: invalid literal for int() with base 10:

因此,我建议您更轻松地使用try/except来尝试将您的值转换为float。如果它不起作用,则提示用户继续输入值,直到它们为止。然后你只需打破你的循环并返回你的数字,输入一个浮动类型。

此外,由于使用了try / except,您不再需要在while循环中进行条件检查。您只需将循环设置为while True,然后在代码中满足条件后再中断。

观察以下代码重写我上面提到的代码:

def GetVolume():
    print("How many cublic cm of water does the item displace")
    Volume = input()
    while True:
        try:
            Volume = float(Volume)
            break
        except:
            print("You have to type a value")
            Volume = input()
    return Volume

答案 1 :(得分:0)

def GetVolume():
    Volume = input("How many cublic cm of water does the item displace")

    while not Volume.replace('.', '').replace(',', '').isdigit():
        Volume = input("You have to type a value")
    return float(Volume)

x = GetVolume()
print(x)

答案 2 :(得分:0)

你必须修改你的while,因为验证是str还是不同于int。默认情况下,输入将始终为str,除非您在案例中使用int()或float()修改了类型。

您可以使用'尝试'而是检查这个:

while True:
    x = input("How many cubic cm of water does the item displace")

    try:
        x = float(x)
        break

    except ValueError:
        pass

print('out of loop')