如何确保用户输入了数字?
How to make sure that a user inputs a number?
我已经编写了一个 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=")
这就是 str.isdigit
的用途:
while( not measure.isdigit()) :
measure =input("Please type numbers only ")
您可以简单地使用 try, except 循环和 while 循环。这就是我的意思:
intweight = 0
while True:
try:
weight = float(input())
except ValueError:
print "Please enter a number"
else:
break
intweight = weight
while 循环将强制用户输入一个字符串,直到它只包含数字。该程序将尝试将字符串转换为数字。如果有字母,except 部分将被激活。如果转换成功,else 部分将激活,从而打破循环。希望对您有所帮助!
我已经编写了一个 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=")
这就是 str.isdigit
的用途:
while( not measure.isdigit()) :
measure =input("Please type numbers only ")
您可以简单地使用 try, except 循环和 while 循环。这就是我的意思:
intweight = 0
while True:
try:
weight = float(input())
except ValueError:
print "Please enter a number"
else:
break
intweight = weight
while 循环将强制用户输入一个字符串,直到它只包含数字。该程序将尝试将字符串转换为数字。如果有字母,except 部分将被激活。如果转换成功,else 部分将激活,从而打破循环。希望对您有所帮助!