python - 我的 python 代码做了它打算做的事情,但是中断/继续使用 try/catch 块?
问题描述
#A 0-50 Units is multiplied by $0.59 (multiply by 0.59)
#B Up to 150 Units (minus 50 and multiply remaning by 0.65)
#C Greater than 150 Units(minus 150(first 150 = $94.50) and multiply remaining by 0.68)
#D All Residential charges are fixed @ $13.00(always add $13)
print (" * SKELEC Electricity Bill Calculator * ")
def main():
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if prev_month < 0:
print("Please enter a valid reading.")
main()
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if pres_month < 0:
print("Please enter a valid reading.")
main()
if pres_month < prev_month:
print("Present month value is lower than previous month value")
main()
units_kwh = pres_month - prev_month #Variable for the subtraction of present month and previous month
print("Usage = ", units_kwh,"kw/h")
if units_kwh <= 50: #Argument for 0-50 kwh units
Energy_charge = units_kwh * 0.59
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 50 and units_kwh <= 150: #Argument for units up to 150kwh
units_fifty = units_kwh - 50
Energy_charge = (units_fifty * 0.65 + 29.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 150: #Argument for units over 150kwh
Energy_charge = ((units_kwh - 150) * 0.68 + 94.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
print("Residential Charge of $13.00 added")
main()
一切正常,但如果一开始输入了不正确的值(例如字符),一旦给出最终结果,代码就会不必要地循环。我尝试将 try/catch 块移到循环之外,仔细检查我的条件语句并校对以查看代码如何以这种方式循环。我确信问题出在 try/catch 块中,但我对使用 Python 编码还很陌生,所以我不确定如何解决这个问题?
解决方案
您可以进行一些更改以改进代码:
- 如果用户输入负数,则引发异常
- 为条件添加一个外
while
循环pres_month < prev_month
试试这个代码:
def main():
while True: # pres_month < prev_month
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
if prev_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
if pres_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
if pres_month < prev_month:
print("Present month value is lower than previous month value")
else:
break # data is valid
推荐阅读
- python - 网页抓取网站不返回正确的值
- css - Vue Js - 排版
- flutter - 检查未来下载的总 Mb
- spring - Spring自定义错误响应:timeStamp vs timestamp
- javascript - 对房子“this”感到困惑,它适用于匿名函数和 const
- javascript - onmouseover 功能对某些标签没有响应?
- flutter - Flutter video_player 无法在 release 版本中播放
- string - 阅读时跳过文件的某些部分
- c - 模式 7 仿射变换中不受控制的摄像机移动的原因是什么?
- python - django:在模板(pk)中引用模型主键的问题