0

我是 Python 的新手。我正在尝试创建一个仅收取最低付款(从 10 开始)并仅返回余额(付款 12 个月后)的函数。

在函数之外,我正在使用一个调用该函数并检查余额是否为零或小于零的循环。如果不是,则增加最低付款 + 10 美元并再次调用该函数。当余额为零或小于零时,打印出最低付款。

理论上输出应该如下:

测试用例 1:

balance = 3329
annualInterestRate = 0.2

Result Your Code Should Generate:

******Lowest Payment: 310******

Test Case 2:

balance = 4773
annualInterestRate = 0.2
Result Your Code Should Generate:

**最低付款:440* *

Test Case 3:

balance = 3926
annualInterestRate = 0.2
Result Your Code Should Generate:

**最低付款:360* *

到目前为止,这就是我所拥有的:

balance = 100
annualInterestRate = 0.2
per_month = ( annualInterestRate / 12 ) 

# Answer is 0.0166666 but I need it to be 0.01, so figured out to convert to string then to float, not the most elegant , but practical. :)

convert_to_str = str(per_month)[:4]
per_month = float(convert_to_str)
lowest_payment = 0

def main():
    i = 0
    while i < 11:
        global balance
        global lowest_payment
        global per_month
        balance = balance - lowest_payment
        balance = ((balance * per_month) + balance)
        i = i +1
        #print (balance)
main()

if balance <= 0 or balance == 0:
    print "Lowest Payment: " + str(lowest_payment)
else:
    lowest_payment = lowest_payment + 10
    main()

问题是没有执行我的功能,然后再次循环。我尝试过使用 if 和 while 循环。在我的while循环下面,给出一个无限循环:

while balance >= 0 or balance != 0:
    lowest_payment = lowest_payment + 10
    main()
    if balance <= 0:
        print "Lowest Payment: " + str(lowest_payment)

非常感谢您的帮助。

4

2 回答 2

1

我找到了……你让我想到了公式……然后把它整理好了。通过了所有12个案例。在我的最终代码下方。

balance = 100
annualInterestRate = 0.2
month_payment = 10
month_interest = annualInterestRate/12

def debt(balance,month_payment,month_interest):
    for i in xrange(12):
        balance = (balance - month_payment)+month_interest*(balance - month_payment)
    return balance

final_bal = 0
i = 0
while final_bal >=0:
    final_bal = debt(balance,month_payment*i,month_interest)
    month_pay = i*month_payment
    i += 1
print 'Lowest Payment: '+str(month_pay)
于 2013-11-01T23:32:44.473 回答
0

你可以这样做:

while balance > 0:    
    lowest_payment = lowest_payment + 10
    main()
print "Lowest Payment: " + str(lowest_payment)

您可能希望根据您的问题需要对其进行修改。

于 2013-11-01T21:26:20.867 回答