我的循环没有调用我的函数

时间:2013-11-01 21:10:50

标签: function loops python-2.7 while-loop infinite-loop

我是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)

非常感谢您的帮助。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

你可以这样做:

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

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