在Python中的每次迭代之后添加for循环的结果

2024-09-27 07:33:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始学习编码,从Python开始。在我的Python课程中,我遇到了以下问题:

Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.

The following variables contain values as described below:

balance - the outstanding balance on the credit card

annualInterestRate - annual interest rate as a decimal

monthlyPaymentRate - minimum monthly payment rate as a decimal

For each month, calculate statements on the monthly payment and remaining balance, and print to screen something of the format:

Month: 1
Minimum monthly payment: 96.0
Remaining balance: 4784.0

(我把那部分搞定了)

Finally, print out the total amount paid that year and the remaining balance at the end of the year in the format:

Total paid: 96.0 Remaining balance: 4784.0

(这是总付费的一部分,我经过许多小时的尝试和搜索无法解决)

所以我需要做的是:把每月最低付款额的所有结果加起来,得到所付的总额。在

这是我的代码:

def creditPayment(balance, annuelInterestRate, monthlyPaymentRate):

    for month in range(1, 13):

        monthlyInterestRate = annuelInterestRate/ 12.0
        minimumMonthlyPayment = monthlyPaymentRate * balance
        monthlyUnpaidBalance = balance - minimumMonthlyPayment
        balance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)

        totalPaid = sum((minimumMonthlyPayment) for _ in  range(0, 13))  

        print 'Month: ', month
        print 'Minimum monthly payment: ', round(minimumMonthlyPayment, 2)
        print 'Remaining balance: ', round(balance, 2)
        print ' '
    print 'Total paid: ', round(totalPaid, 2)
    print 'Remaining balance: ', round(balance, 2)

print creditPayment(4213, 0.2, 0.04)

一切都很好,除了总支付额加起来只有最低月供第一值的12倍。我不能再好了。在


Tags: andtheaspaymentcardyearprintbalance
2条回答

如果我正确地解释了你的问题,我假设你的意图是每个月增加totalPaid,每个月minimumMonthlyPayment。如果是:

totalPaid = 0.0
for month in range(1, 13):
    #
    # Other stuff you're doing in the loop
    #
    totalPaid += minimumMonthlyPayment

每次通过循环,totalPaid都会增加为该特定月份计算的最低付款额。当然,如果你想增加除最低支付额以外的任何费用都要支付的情况,这种逻辑必须改变/扩大。在

在for循环中,您有:

totalPaid = sum((minimumMonthlyPayment) for _ in  range(0, 13))

这是将totalPaid设置为minimumMonthlyPayment的13倍,就像循环的迭代一样,因此在最后一个循环中,该值被设置为最后一个最小付款的13倍。您需要在每次迭代的totalPaid中添加一个值,以便在添加之前更新该值。以下是我将代码更改为:

^{pr2}$

另外,由于您没有在for _ in range(0, 13)中使用迭代器的实际值,所以只使用range(13)会更具可读性。我想你可能想让它循环12次,因为你的程序的其余部分都是这样。在

相关问题 更多 >

    热门问题