作业Python问题

2024-09-27 07:29:34 发布

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

下面的代码不起作用,我很沮丧。我知道正确的输出应该是$310,但不知何故我的代码没有达到。这是edex课程介绍CS和python的家庭作业。我试着评论我认为代码在做什么,但显然我是不对的。在

任何帮助或提示将不胜感激。在

balance = 3329
annualInterestRate = 0.2
monthInterest = annualInterestRate/12.0

# simple payment for the month
monthlyPaymentRate = 10

# while this is true, run the for loop from 1 - 12. This loop will break if the balance gets <     0, otherwise the 
# monthly payment rate adds by 10 each year. 
while True:
    for month in range(1, 13):
        balance = balance - monthlyPaymentRate
        interestBalance = balance + (monthInterest*balance) 
        balance = interestBalance
        if balance < 0:
            break
        else:
            monthlyPaymentRate += 10

print "balance = " + str(balance)
print "annualInterestRate = " + str(annualInterestRate)

print"Lowest payment: " + str(monthlyPaymentRate)

Tags: the代码loopforifpaymentprintbalance
1条回答
网友
1楼 · 发布于 2024-09-27 07:29:34

非常感谢您的评论,我能够调整我的代码以获得适当的结果,通过创建一个函数,我可以测试一年中每月支付率的结果,返回一个结果,如果结果不是我想要的,我将在while循环中重新运行代码。棘手的业务这学习代码但相当有趣。在

任何关于清洁或效率的想法都是最受欢迎的,很肯定这不是最有效的步骤。在

balance = 4400
annualInterestRate = 0.18
monthInterest = annualInterestRate/12.0

# simple payment for the month
monthlyPaymentRate = 0

# while the balance is greater than zero, run the for loop from 1 - 12. This loop will break if 
# the balance gets <=0, otherwise the monthly payment rate adds by 10 each year.
while balance > 0:
    monthlyPaymentRate += 10
    def testBalance(balance, monthlyPaymentRate):
        for month in range(1, 13):
            balance = balance - monthlyPaymentRate
            interestBalance = balance + (monthInterest*balance)
            balance = interestBalance
        return balance

    if testBalance(balance, monthlyPaymentRate) <= 0:
        break

print"Lowest Payment: " + str(monthlyPaymentRate)

相关问题 更多 >

    热门问题