我正在编写一个程序,使用以下公式计算复利:p(1+I)n
从用户输入中获取本金、利息和年数
我编写了以下方法:
def is_valid_entries(principle, int_rate, years):
try:
#Convert the inputs from string to respective data type
principal_float = float(principle)
rate_float = float(int_rate)
years_int = int(years)
if not (0 < rate_float < 1.0):
return False, "The interest rate must be between 0.00 to 1.00"
return True, (principal_float, rate_float, years_int)
except ValueError:
return False, "Could not convert data to the appropriate data type"
except:
return False, "Unknown error"
然而,我的问题是,当我报告异常时,我希望非常具体。例如,如果本金有一个转换错误,我想报告在转换本金时有一个错误,利率和年限也遵循同样的逻辑。请让我知道如何在异常处理中做到这一点,或者是否有更好的方法来编写这篇文章
通常,您必须将
try
块最小化到特定的行,以使其看起来像这样:当然,正如你所看到的,这很可怕。改进的提示是
repeating code == functions
,因此最好将其包装到函数中:现在,您的主代码可以如下所示:
这样,您可以根据每个输入获得特定的消息
*删除空白^ {< CD3>},因为在代码
中没有其他异常出现。你只是缺少了“提升”的关键词。你可能不想把整个事情都放在这样一个try块中,你只想在某些地方使用raise而不是return
例如,您有:
你可以说:
这将引发以字符串形式返回的消息的值错误。如果有人在try块中调用您的函数,他们可以处理ValueError异常
https://docs.python.org/3/tutorial/errors.html
相关问题 更多 >
编程相关推荐