【发布时间】:2020-07-26 05:01:03
【问题描述】:
我的任务是以两种方式计算储蓄账户中的金额并比较结果。它提示用户输入原则,利率(百分比)和投资年限。我需要使用try-except块来验证输入,并使用while语句提示用户直到输入有效。我在验证和过程中有问题。当我输入无效时,它没有按预期打印相关的异常错误。功能部分正常,忽略它们。此外,“Going around again”应该在下一个提示输入之前打印,但我的出现在正确输入执行结束时。请你帮助我好吗?谢谢。
def calculate_compound_interest(principle, int_rate, years):
value = principle * (1 + int_rate)**years
return value
def calculate_compound_interest_recursive(principle, int_rate, years):
if years == 0:
return principle
else:
recursive_value = calculate_compound_interest_recursive(principle, int_rate, years-1)*
(1+int_rate)
return recursive_value
def format_string_output(value, recursive_value):
return "Interest calculated recursively is {:,.2f} and calculated by original formula is
{:,.2f}.These values are a match.".format(recursive_value,value)
print(__name__)
if __name__ == "__main__":
while True:
principle_input = input("Please input principle:")
interest_rate_input = input("Please input interest rate with %:")
years_input = input("Please input years:")
try:
p = float(principle_input)
i = (float(interest_rate_input.replace("%","")))/100
n = int(years_input)
except ValueError():
print("Error: invalid principle.")
except ValueError():
print("Error: invalid interest rate.")
except ValueError():
print("Error: invalid years.")
else:
print(calculate_compound_interest(p, i, n))
print(calculate_compound_interest_recursive(p, i, n))
print(format_string_output(calculate_compound_interest(p, i, n),
calculate_compound_interest_recursive(p, i, n)))
break
finally:
print("Going around again!")
【问题讨论】:
标签: python validation while-loop try-catch except