首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python异常处理- BMI计算器

Python异常处理- BMI计算器
EN

Stack Overflow用户
提问于 2022-09-07 01:34:46
回答 2查看 81关注 0票数 -1

我正在编写python中的BMI计算器,并希望添加异常处理。我创建了两个函数。一种是高度转换器,根据用户的输入将高度转换为英尺或米,另一种是重量转换器,根据输入将用户的体重转换为千克或磅。def height_converter(h)和weight_converter(w)函数在用户输入错误时不会重新启动,而下面的代码只要求输入重量和高度。另外,BMI变量返回一个错误,我不知道该做什么。

代码语言:javascript
运行
复制
# BMI CALCULATOR IN PYTHON
import os
from datetime import datetime
# define our clear function
def clear():
    # for windows
    if os.name == 'nt':
        os.system('cls')
    # for mac and linux(here, os.name is 'posix')
    else:
        _ = os.system('clear')
def weight_converter(w):
    while True:
        try:
            global converted
            converted = 0
            weight_unit = input("What is the weight unit Kgs or Lbs: ")
            if weight_unit.upper() == "KG":
                converted = w / 1
                print("weight in kg is: ", converted)
            elif weight_unit.upper() == "LBS":
                converted = w / 2.2
                print("weight in kg is: ", converted)
            else:
                raise ValueError(weight_unit)
            break
        except (ValueError, IOError, IndexError):
            print("ERROR")
            return converted
def height_converter(h):
    while True:
        try:
            height_unit = input("what is the height unit meters or feet: ")
            if height_unit.upper() == "METERS":
                converted = h / 1
                print("height in meters is: ", converted)
            elif height_unit.upper() == "FEET":
                converted = h / 3.281
                print("height in meters is: ", converted)
            break
        except(ValueError,IOError,IndexError):
            print("ERROR")
        return converted
while True:
    try:
        age = input("How old are you? ")
        age = int(age)

        weight = input("What is your weight: ")
        weight = float(weight)
        wconverted = weight_converter(weight)
      
        height = input("What is your height: ")
        height = float(height)
        hconverted = height_converter(height)
        break
    except ValueError:
        # os.system(clock_settime)
        print("No valid integer! Please try again ...")
        clear()
BMI = float(wconverted / (hconverted ** 2))
print("Your BMI is: ", BMI, "as of ", date) 
print("You are using a", os.name, "system")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-07 03:00:46

测试您的代码,在转换函数中,代码块末尾的返回操作实际上没有被执行,因为它在代码块缩进中的逻辑位置。因此,您实际上是向调用这些函数的语句返回一个"None“。

考虑到这一点,下面是您的代码,通过一些调整从权重和高度转换函数返回转换后的值。

代码语言:javascript
运行
复制
# BMI CALCULATOR IN PYTHON
import os
from datetime import date
# define our clear function
def clear():
    # for windows
    if os.name == 'nt':
        os.system('cls')
    # for mac and linux(here, os.name is 'posix')
    else:
        _ = os.system('clear')
def weight_converter(w):
    while True:
        try:
            global converted
            converted = 0
            weight_unit = input("What is the weight unit Kgs or Lbs: ")
            if weight_unit.upper() == "KG":
                converted = w / 1
                print("weight in kg is: ", converted)
                return converted            # Made sure a decimal value was being returned
            elif weight_unit.upper() == "LBS":
                converted = w / 2.2
                print("weight in kg is: ", converted)
                return converted            # Same here
            else:
                raise ValueError(weight_unit)
            
        except (ValueError, IOError, IndexError):
            print("ERROR - Please enter proper unit of measure")
            
def height_converter(h):
    while True:
        try:
            height_unit = input("what is the height unit meters or feet: ")
            if height_unit.upper() == "METERS":
                converted = h / 1
                print("height in meters is: ", converted)
                return converted            # And here
            elif height_unit.upper() == "FEET":
                converted = h / 3.281
                print("height in meters is: ", converted)
                return converted            # And finally here
            else:
                raise ValueError(height_unit)
        except(ValueError,IOError,IndexError):
            print("ERROR - Please enter proper unit of measure")
        
while True:
    try:
        age = input("How old are you? ")
        age = int(age)

        weight = input("What is your weight: ")
        weight = float(weight)
        wconverted = weight_converter(weight)
      
        height = input("What is your height: ")
        height = float(height)
        hconverted = height_converter(height)
        break
    except ValueError:
        # os.system(clock_settime)
        print("No valid integer! Please try again ...")
        clear()
BMI = float(wconverted / (hconverted ** 2))
print("Your BMI is: ", BMI, "as of ", date.today())     # You had not defined the variable "date"
print("You are using a", os.name, "system")

我使用了一种蛮力方法来确保返回一个值。或者,您可以将函数块中的最后一个返回细化为只有一个返回,但我只是希望在提供快速调整时避免可能出现的范围问题。

这就产生了以下示例结果。

代码语言:javascript
运行
复制
@Una:~/Python_Programs/BMI$ python3 Calculator.py 
How old are you? 66
What is your weight: 170
What is the weight unit Kgs or Lbs: lb
ERROR - Please enter proper unit of measure
What is the weight unit Kgs or Lbs: kilos
ERROR - Please enter proper unit of measure
What is the weight unit Kgs or Lbs: lbs
weight in kg is:  77.27272727272727
What is your height: 5.83333
what is the height unit meters or feet: inches
ERROR - Please enter proper unit of measure
what is the height unit meters or feet: feet
height in meters is:  1.7779122218835721
Your BMI is:  24.445876294351564 as of  2022-09-08
You are using a posix system

试试看。

票数 0
EN

Stack Overflow用户

发布于 2022-09-07 02:30:30

在您的weight_converter函数中,只有当用户输入错误输入时,才会返回转换后的值。在Python中,indention确定语句属于哪个代码块。您需要将返回语句放置在与need相同的缩进级别上:这将使它位于while循环之外,并且它基本上会在您中的一个中断之后发生。

height_converter函数也有类似的问题。

另外,您只在其中一个函数中引发ValueError,并且由于在not块中捕获它们,它们不会传播到调用方。

对此代码的异常处理似乎增加了不必要的复杂性。仅仅为了让下一行代码做一些不同的事情而引发一个ValueError是过分的和令人困惑的。下面是weight_converter函数的一个更简单的版本。

代码语言:javascript
运行
复制
def weight_converter(w):
    while True:
        weight_unit = input("What is the weight unit Kgs or Lbs: ")
        if weight_unit.upper() == "KG":
            conversion = 1.0
            break
        elif weight_unit.upper() == "LBS":
            conversion = 2.2
            break
        else
            print("ERROR")
    converted = w / conversion
    print("weight in kg is: ", converted)
    return converted

未登录的异常会在调用堆栈中传播,直到它们被一个except块捕获为止。如果它们未被捕获,则会导致解释器停止程序,并通常打印堆栈跟踪。如果此代码导致异常,则调用方中的异常处理程序将捕获它们。如果您在此函数中捕获它们,它们将永远无法补偿调用方。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73629204

复制
相关文章

相似问题

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