我刚开始学习python,我想知道如何做我在标题中说过的话。在编程方面,我唯一的背景是一个学期长的C++课程,我在高中的时候拿到了C,几乎什么都忘了。这是我的密码:
while True:
try:
height_m = float(input("Enter your height in meters: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
while True:
try:
weight_kg = float(input("Enter your weight in kilograms: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
bmi = weight_kg / (height_m ** 2)
print ("Your bmi is",(bmi),".")
if bmi < 18.5:
print ("You are underweight.")
elif 18.5 <= bmi <=24.9:
print ("You are of normal weight.")
elif 25 <= bmi <= 29.9:
print ("You are overweight.")
else:
print ("You are obese.")如你所见,这只是一个基本的BMI计算器。然而,我想做的是,如果有人输入"1.8米“、"1.8米”或"1.8米“,相当于公斤,程序就会删除额外的输入,就像他们没有添加那样。另外,你给我的任何额外的建议都会很棒。谢谢!
发布于 2018-06-14 04:50:02
将第三行改为:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))它的工作方式是在转换为浮动之前移除所有的字母。
https://stackoverflow.com/questions/50849790
复制相似问题