[英]Python Exception Handling - BMI CALCULATOR
我正在 python 中編寫一個 BMI 計算器,並想添加異常處理。 我創建了兩個函數 1. 一個高度轉換器,根據用戶的輸入將高度轉換為英尺或米,以及一個重量轉換器,根據輸入將用戶的體重轉換為公斤或磅。 當用戶輸入錯誤的輸入時,def height_converter(h) 和 weight_converter(w) 函數不會重新啟動,這與下面的代碼不同,它只詢問體重和高度。 另外,BMI變量返回錯誤,我不知道該怎么辦了
# 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")
在您的 weight_converter function 中,您只會在用戶輸入錯誤輸入時返回轉換后的值。 在 Python 中,縮進決定了語句屬於哪個代碼塊。 您需要將 return 語句放在與 while True 相同的縮進級別:這將它放在 while 循環之外,並且它基本上會在你們中的一個人休息后發生。
height_converter function 也有類似的問題。
此外,您僅在其中一個函數中引發 ValueError ,並且由於您在 except 塊中捕獲它們,因此它們不會傳播到調用者。
這段代碼的異常處理似乎增加了不必要的復雜性。 僅僅為了讓下一行代碼做一些不同的事情而引發 ValueError 是矯枉過正和令人困惑的。 這是一個更簡單的 weight_converter function 版本。
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 塊捕獲。 如果它們沒有被捕獲,它們會導致解釋器停止程序並通常打印堆棧跟蹤。 如果此代碼導致異常,它們將被調用者中的異常處理程序捕獲。 如果您在此 function 中抓住它們,它們將永遠無法彌補調用者的損失。
測試您的代碼,在轉換函數中,代碼塊末尾的返回操作實際上並未被執行,因為它在邏輯上位於代碼塊的縮進中。 因此,您實際上是在向調用這些函數的語句返回“無”。
考慮到這一點,以下是您的代碼,其中進行了一些調整,以從體重和身高轉換函數返回轉換后的值。
# BMI CALCULATOR IN PYTHON
import os
from datetime import date # FYI, I revised this a bit as well for the 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)
break
except (ValueError, IOError, IndexError):
print("ERROR")
return 0.0
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
break
except(ValueError,IOError,IndexError):
print("ERROR")
return 1.0
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")
我應用了蠻力方法來確保返回值。 或者,您可以將 function 塊中的最后一個返回改進為只有一個返回,但我只是想避免在提供快速調整時可能出現的 scope 問題。
這產生了以下示例結果。
@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: lbs
weight in kg is: 77.27272727272727
What is your height: 5.83333
what is the height unit meters or feet: feet
height in meters is: 1.7779122218835721
Your BMI is: 24.445876294351564 as of 2022-09-06
You are using a posix system
試試看。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.