我写了一个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=")
这是^{} 的用途:
您可以简单地使用try,除了循环加上while循环。我的意思是:
while循环将强制用户输入一个字符串,直到它只有数字为止。程序将尝试将字符串转换为数字。如果有字母,则“例外”部分将被激活。如果转换成功,else部分将激活,中断循环。我希望这对你有帮助!在
相关问题 更多 >
编程相关推荐