如何确保用户输入一个数字?

2024-10-01 05:02:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个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=")

Tags: orandtoinforinputtypemetric
2条回答

这是^{}的用途:

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

您可以简单地使用try,除了循环加上while循环。我的意思是:

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

while循环将强制用户输入一个字符串,直到它只有数字为止。程序将尝试将字符串转换为数字。如果有字母,则“例外”部分将被激活。如果转换成功,else部分将激活,中断循环。我希望这对你有帮助!在

相关问题 更多 >