【问题标题】:how can i handle value error exceptions many times in python [duplicate]我如何在python中多次处理值错误异常[重复]
【发布时间】:2021-10-25 14:36:26
【问题描述】:

我正在尝试编写一个 BMI 计算器。我试图确保用户输入只是一个浮点数,所以我使用了except,但我无法让它循环检查。

def error_handeling():
    try:
        weight = float(input("enter your weight in KG : "))
    except ValueError:
        weight = float(input("enter your REAL weight in KG : "))

for i in range(100):
    error_handeling()

while weight < 2.0:
    print("enter a valid weight")
    weight = float(input("enter your weight in KG : "))
    if False:
        break


height = float(input("enter your height in Meters: "))


while height < 0.5 or height > 2.2:
    print("enter a valid height ")
    height = float(input("enter your height in meters : "))
    if False:
        break


BMI = weight / (height**2.0)

print("your bmi is : " + str(BMI))

if BMI < 18.5:
    print("you're underweight EAT MORE !!")
if BMI > 18.5:
    print("you're overweight EAT LESS + practise sport !!")
if BMI == 18.5:
    print("you're in perfect weight")

【问题讨论】:

  • @not_speshal 我试图强制用户输入浮点数或整数,然后它将自动转换为浮点数,我不希望用户输入单词而不是号码

标签: python loops exception


【解决方案1】:

用这个替换你的error_handling函数:

def get_weight():
    while True:
        try:
            weight = float(input("enter your weight in KG : "))
            return weight
        except ValueError:
            print("please enter a valid number.")

并在需要用户体重时致电get_weight

这样它会一遍又一遍地询问重量,直到用户提供一个好的答案。

【讨论】:

  • @user17242583 效果很好,非常感谢
  • 不客气!!
猜你喜欢
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多