Calculating and printing a credit card balance I am working on a problem that simply calculates and prints the credit card balance. I hope this code can be improved/optimized a lot.

I am from a Java background. If it was Java code, I would have pulled all the code lines inside the for loop and place it at the beginning of the method and inside for loop I would call the method recursively. I tried to do the same in python but it hit me with some error:


  RuntimeError: maximum recursion depth exceeded while calling a Python object


From a quick internet search I found that it is better to go for iteration instead of recursion:

'''
Program to calculate credit card balance after 1 year
'''
def calculateCreditCardBalance(balance, annualInterestRate, monthlyPaymentRate):

    totalPaid = 0

    for thisMonth in range(1,13):
        monthlyInterestRate = annualInterestRate / 12.0
        minimumMonthlyPayment = round(monthlyPaymentRate * balance, 2)
        monthlyUnpaidBalance = balance - minimumMonthlyPayment
        updatedBalanceEachMonth = round(monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) , 2) 

        print 'Month: %d' %(thisMonth)
        print 'Minimum monthly payment: ' + str(minimumMonthlyPayment)
        print 'Remaining balance: ' + str(updatedBalanceEachMonth)

        balance = updatedBalanceEachMonth
        totalPaid += minimumMonthlyPayment

    print 'Total paid: ' + str(totalPaid)
    print 'Remaining balance: '+ str(balance)


calculateCreditCardBalance(4842, 0.2, 0.04)
A good thing you can do is to create more functions, which return values in the dictionary form.

Pseudo-code:

def calculateCreditCardBalance(balance, annual_interest_rate, monthly_payment_rate):
    total_paid = 0
    curr_values = ["balance" =&gt; balance, "annual_interest_rate" =&gt; annual_interest_rate, "monthly_payment_rate" =&gt; monthly_payment_rate]
    foreach this_month in rage(1,13):
        month_values = calculate_month_values(curr_values)
        print_values(month_values)
        update_month_values(month_values,curr_values)
    print 'Total paid: ' + str(curr_values["total_paid"])
    print 'Remaining balance: '+ str(curr_values["total_paid"])