2013-10-16 78 views
1

我想在python中製作一個計算信用卡上剩餘餘額的程序。它用於MIT開放課件"Introduction to Computer Science and Programming"。我在做problem set one如何更改python for循環中的變量?

程序必須要求用戶啓動變量:起始餘額,年利率和最低月度支付。 這是我的代碼。

initialOutstandingBalance= float(raw_input('What is the outstanding balance on your 
card?')) 
annualInterestRate=float(raw_input('What is the annual interest rate expressed as a 
decimal?')) 
minimumMonthlyPaymentRate=float(raw_input('What is the minimum monthly payment rate on 
your card expressed as a decimal?')) 

for month in range(1,13): 
    print("Month: "+ str(month)) 
    minimumMonthlyPayment=float(minimumMonthlyPaymentRate*initialOutstandingBalance) 
    interestPaid=float((annualInterestRate)/(12*initialOutstandingBalance)) 
    principalPaid=float(minimumMonthlyPayment-interestPaid) 
    newBalance=float(initialOutstandingBalance-principalPaid) 
    print("Minimum monthly payment: $"+str(minimumMonthlyPayment)) 
    print("Principle paid: $"+str(principalPaid)) 
    print("Remaining Balance: $"+str(newBalance)) 

如何獲得剩餘餘額以正確更新?我無法弄清楚如何在每個月底更新餘額。到目前爲止,每個月的最低月還款額,本金支付和剩餘餘額都會返回相同的值。

回答

0

您在整個循環中使用相同的initialOutstandingBalance變量,並且永遠不會更改它。相反,您應該跟蹤當前的餘額。這將等於循環開始時的初始未結餘額,但會在運行時發生變化。

你也不需要一直打電話float

current_balance = initialOutstandingBalance 
for month in range(1,13): 
    print("Month: "+ str(month)) 
    minimumMonthlyPayment = minimumMonthlyPaymentRate * current_balance 
    # this calculation is almost certainly wrong, but is preserved from your starting code 
    interestPaid = annualInterestRate/(12*current_balance) 
    principalPaid = minimumMonthlyPayment - interestPaid 
    current_balance = current_balance - principalPaid 
    print("Minimum monthly payment: $"+str(minimumMonthlyPayment)) 
    print("Principle paid: $"+str(principalPaid)) 
    print("Remaining Balance: $"+str(current_balance)) 
0

你要保持變量newBalance外循環,否則它會被重新分配每個迭代。此外,您不希望將利率除以餘額的12倍,而是將其除以12,然後將商數乘以餘額。最後,如上所述,您不需要所有的float

這應該工作:

newBalance = initialOutstandingBalance 

for month in range(1,13): 
    print("Month: " + str(month)) 

    minimumMonthlyPayment = minimumMonthlyPaymentRate * newBalance 
    interestPaid = annualInterestRate/12 * newBalance 
    principalPaid = minimumMonthlyPayment - interestPaid 
    newBalance -= principalPaid 

    print("Minimum monthly payment: $" + str(minimumMonthlyPayment)) 
    print("Principle paid: $" + str(principalPaid)) 
    print("Remaining Balance: $" + str(newBalance))