使用循环在python中重新运行代码

时间:2015-09-09 19:46:05

标签: python

我是python的新手,最近我遇到了一个问题。问题要求编写一个代码,选择最低的每月付款率,以便在年底前,余额为0或负数。

解决这个问题的计划是首先假设每月付款的价值,然后在年底找到余额,同时考虑每月的利息。然后,编写代码将余额比较为0或负数。如果余额仍有正值,那么代码将在每月付款中加10,并继续重复,直到余额为0或为负。

粘贴是我的代码。我可以想到它背后的逻辑,但是我的代码在每个月12岁时停止,并且它不能继续,我不知道如何让代码重新运行计算。

balance = 3329
a = balance
annualInterestRate = 0.2
monthly_interest_rate = (annualInterestRate)/12.0

monthlyPaymentRate = 10

month = 1
total = 0

while (month < 13):
    monthly_unpaid_balance = (balance) - (monthlyPaymentRate)
    updated_balance_each_month = (monthly_unpaid_balance) + (monthly_interest_rate * monthly_unpaid_balance)
    round (updated_balance_each_month,2)
    unpaid= updated_balance_each_month
    month = month + 1
    balance=unpaid
    total = total + balance

    if (total >0 ):
        balance=a
        monthlyPaymentRate=monthlyPaymentRate+ 10

1 个答案:

答案 0 :(得分:0)

您需要在检查if (unpaid > 0)的if语句中将月份重置为1,但您还需要检查if(month == 13)。最重要的是,每次循环时,您都会将a设置为balance。试试这个

balance = 3329
a=balance
annualInterestRate = 0.2
monthly_interest_rate= (annualInterestRate)/12.0
monthlyPaymentRate=10

month=1
total=0
unpaid = 1

while unpaid > 0:

     monthly_unpaid_balance = (balance) - (monthlyPaymentRate)
     unpaid = round((monthly_unpaid_balance + monthly_interest_rate * monthly_unpaid_balance), 2)
     #Your round line doesn't do anything since it returns the new answer but you don't assign it to anything. That being said, it's an unnecessary line and will work without the rounding


     month += 1
     balance=unpaid
     total += monthlyPaymentRate


     if (unpaid > 0 and month == 13):
         balance=a
         monthlyPaymentRate += 10
         month = 1

print(monthlyPaymentRate)

我认为这就是你所要求的。所以它的作用是它仅在上个月检查未支付的金额。如果它大于零并且已经过了所有12个月,那么它会将余额重置为原始版本,并balance = a10添加到monthlyPaymentRate并将月份重置为{{} 1}}。如果它小于零,则它将跳出while循环并打印1