如何确保用户输入数字?

时间:2015-01-31 14:18:52

标签: python validation python-3.x user-input

我已经写了一个BMI计算器,但我希望有一种方法可以确保用户只输入数字,这样,如果输入其他内容,则会再次询问该问题。这是我的一些代码。

#Ask whether metric or imperial is to be used and ensures no typing errors
measure = input("Would you like to use Metric or imperial measurements? Please type i for imperial or m for metric  \n")

while(measure != "i") and (measure != "m"):
    measure =input("Please type a valid response. Would you like to use Metric or imperial measurements? Please type i for imperial or m for metric")

#Asks the users weight
if(measure == "i"):
    weights = input("Please type in your weight in stones and pounds- stones=")
    weightlb = input("- pounds=")
    weights = int(weights)
    weightlb = int(weightlb)
    weight = (weights*14)+weightlb

elif(measure == "m"):
    weight = input("Please type in your weight in kilograms=")

2 个答案:

答案 0 :(得分:2)

你可以简单地使用try,除了循环和while循环。这就是我的意思:

intweight = 0
while True:
    try: 
        weight = float(input())
    except ValueError:
        print "Please enter a number"
    else:
        break
        intweight = weight

while循环将强制用户输入一个字符串,直到它只有数字。程序将尝试将字符串转换为数字。如果有字母,则将激活除外部分。如果转换成功,则else部分将激活,从而打破循环。我希望这可以帮助你!

答案 1 :(得分:1)

它是str.isdigit的用途:

while( not measure.isdigit()) :
     measure =input("Please type numbers only ")