開始使用免費開始

重構程式碼

在程式碼審查後,你決定依照軟體工程的最佳實務來重構程式碼。舉例來說,總付款期數不應小於 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 ____
編輯並執行程式碼