<p>我想如果你在下面输入以下语句</p>
<p><code>monthlyPrincipal.append(principal)</code></p>
<p><code>loanAmount -= principal</code></p>
<p>然后你就会得到你想要的结果。你知道吗</p>
<p>编辑:只是一个建议,为了得到更准确的每月付款,我从维基百科得到了一个公式来计算每月付款给定的初始贷款金额。你知道吗</p>
<p>这是一个使用这个公式的程序。你知道吗</p>
<pre><code>import matplotlib.pyplot as plt
# https://stackoverflow.com/questions/52845238/python-looping-issue-with-variable-not-being-assigned-to-on-certain-iteration
loanAmount = 500000.0
interestRate = 3.5
loanTerm = 30 # 30 years
loanTermMonths = loanTerm * 12 # 360 months
i = interestRate / 12 * .01
n = loanTermMonths
# get cash flows, (monthly payments), for Present Value of loanAmount
# https://en.wikipedia.org/wiki/Present_value
monthlyPayment = loanAmount * i / (1 - (1 + i)**(-n))
principal = loanAmount
monthlyInterest = []
monthlyPrincipal = []
for x in range(loanTermMonths):
interest = principal * i
monthlyInterest.append(interest)
principalPortion = monthlyPayment - interest
monthlyPrincipal.append(principalPortion)
principal -= principalPortion
x1 = list(range(1, loanTermMonths+1))
y1 = monthlyInterest
x2 = list(range(1, loanTermMonths+1))
y2 = monthlyPrincipal
plt.plot(x1, y1, label = "Interest")
plt.plot(x2, y2, label = "Principal")
plt.title('Loan Amortization')
plt.grid(True)
plt.xlabel('months')
plt.ylabel('$')
plt.show()
</code></pre>
<p>除了如何计算每月付款外,它和你的大致相同。你知道吗</p>