重构代码
在代码评审后,您决定按照软件工程最佳实践来重构代码。例如,总还款期数不应小于 0。若出现这种情况,请抛出错误。
本练习是课程的一部分
案例研究:用 Python 构建软件
练习说明
- 使用表示贷款总月数的变量补全错误判断条件。
- 如果每月还款次数小于 0,则抛出
ValueError。 - 返回贷款金额。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def calculate_loan_amount(monthly_payment, monthly_interest_rate, nbr_payments):
"""
Calculate the loan amount based on the monthly payment, monthly interest rate, and total number of payments.
"""
# Raise an error if the number of total payment is less than zero
if ____ <= 0:
raise ____("The number of payments must be greater than zero.")
loan_amount = (monthly_payment * ((1 + monthly_interest_rate) ** nbr_payments - 1)) / \
(monthly_interest_rate * (1 + monthly_interest_rate) ** nbr_payments)
# Return the loan amount
return ____