How to Use a Monthly Payment Function in Python (3 Examples)

A monthly payment function in Python can be used to calculate the payment required for a given loan amount, interest rate, and loan term. This can be useful for home or car loan calculations, budgeting, or any other financial calculations. This article provides 3 examples of how to use a monthly payment function in Python to help you get started.


You can use the following function in Python to calculate the monthly payments necessary to pay off a certain loan, given the initial size of the loan, duration of the loan, and annual interest rate:

(rate/12) * (1/(1-(1+rate/12)**(-months)))*P

The following examples show how to use this function in different scenarios.

Example 1: Calculate Loan Payments for Mortgage

Suppose a family takes out a mortgage loan for a house with the following details:

  • Mortgage Amount: $200,000
  • Number of Months: 360
  • Annual Interest Rate: 4%

We can use the following code to calculate the necessary monthly loan payment:

#define initial size of loan, duration of loan, and annual interest rate
P = 200000
months = 360
rate = .04

#calculate monthly payment
(rate/12) * (1/(1-(1+rate/12)**(-months)))*P

954.8305909309076

The monthly loan payment is $954.83. This is how much the family must pay each month in order to pay off the $200,000 loan in 360 months.

Example 2: Calculate Loan Payments for Car Loan

Suppose an individual takes out a loan for a car with the following details:

  • Loan Amount: $20,000
  • Number of Months: 60
  • Annual Interest Rate: 3%

We can use the following code to calculate the necessary monthly loan payment:

#define initial size of loan, duration of loan, and annual interest rate
P = 20000
months = 60
rate = .03

#calculate monthly payment
(rate/12) * (1/(1-(1+rate/12)**(-months)))*P

359.3738132812698

The monthly loan payment is $359.37. This is how much the individual must pay each month in order to pay off the $20,000 loan in 60 months.

Example 3: Calculate Loan Payments for Student Loan

Suppose a student takes out a loan for university with the following details:

  • Loan Amount: $40,000
  • Number of Months: 120
  • Annual Interest Rate: 5.2%

We can use the following code to calculate the necessary monthly loan payment:

#define initial size of loan, duration of loan, and annual interest rate
P = 40000
months = 120
rate = .052

#calculate monthly payment
(rate/12) * (1/(1-(1+rate/12)**(-months)))*P

428.18316863206525

The monthly loan payment is $428.18. This is how much the individual must pay each month in order to pay off the $40,000 loan in 120 months.

The following tutorials explain how to perform other common functions in Python:

x