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

2024-09-27 07:31:56 发布

您现在位置: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

Tags: 代码rate余额totaleachbalanceupdated新手
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:56

您需要在检查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 = a添加到10并将月份重置回1。如果它小于零,那么它将跳出while循环并打印monthlyPaymentRate

相关问题 更多 >

    热门问题