首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 3-函数-异常处理

Python 3-函数-异常处理
EN

Stack Overflow用户
提问于 2021-03-21 03:12:24
回答 1查看 50关注 0票数 0

下面这段代码计算用户的Body Mass Index。有一个函数在用户提供了他或她的体重(kg)和身高(m)之后执行计算。还会打印一条包含用户BMI值的消息。

代码还包括一些异常处理,以避免出现错误。例如,如果提供的是字符串而不是数字,或者如果提供的是极值(例如高度大于2.40m),则会打印一条特殊消息(例如,“请正确输入您的身高!)。

代码语言:javascript
复制
def find_bmi(weight,height):
    my_bmi=weight/height**2
    return my_bmi

try:
    weight=float(input("What is your weight (kg)?"))
    if weight < 200:
        height=float(input("What is your height (m)?"))
        try:
            if height < 2.40:
                print("Your BMI is: "+str(round(find_bmi(weight,height),2))+"!!!")        
            else:
                print("Please enter your height correctly!")
        except ValueError:
            print("Enter a number please!")
    else:
        print("Please enter your weight correctly")
except ValueError:
    print("Enter a number please!")

有没有更具Pythonic风格的方式来写这篇文章呢?有没有什么东西可以用更好的方式写出来呢?请记住,我最近开始学习Python!

EN

回答 1

Stack Overflow用户

发布于 2021-03-21 04:08:13

代码语言:javascript
复制
def find_bmi(weight, height):
    return weight/(height**2)

def prompt():
    try:
        weight, height = [float(a) for a in input("Enter space separated 
        weight(kg) and height(m), weight height\n").split()]
        return weight, height
    except ValueError:
        raise Exception("Enter a number please!")

def range_error(weight, height):
    raise Exception("height out of range") if height >= 2.40 else null
    raise Exception("weight out of range") if weight >= 200 else null

weight, height = prompt()
range_error(weight,height) if (height >=2.40 or weight >=200) else print("Your BMI is: "+str(round(find_bmi(weight,height),2))+"!!!")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66725484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档