Calculating balance after interest and expenses


I’m doing this exercise from the book Python for Everyone. It’s this:

Write an algorithm to settle the following question: A bank account starts out with X. Interest is compounded monthly. Every month expenses are withdrawn. After how many years is the account depleted. The numbers are user selectable. Are there values for which the algorithm would not terminate? If so, change the algorithm to make sure it always terminates.

So here it’s the algorithm:

Read balance, annual rate and witdrawal from user
Compute monthly interest rate as the annual rate divided by 12
If monthly rate * balance >= withdrawal amount
Report that the balance will not shrink
Months = 0
While balance is > 0
Compute the amount of interest and ad it to the balance
Reduce the balance by the withdrawal amount
Increase the number of months
Compute the number of years as months divided by 12
Report the number of years.

And I decided to code the algorithm just to practise.

balance = int(input("What is your balance?: "))
interest = int(input("What's monthly interest?: "))
expenses = int(input("What are your monthly expenses?: "))
months = 0
interestPerMonth = interest / 12 / 100

if (balance * interestPerMonth) >= expenses :
    print("The balance will not shrink over time")

else :
    while balance > 0 :
        interest = balance * interestPerMonth
        balance += interest
        balance -= expenses
        print("Month: ", months, "Balance: ", balance)
        months += 1

years = months / 12
print ("The account will be depleted in: ", years, "years")

And I’d like to know if this looks good. It works, I just would like to improve it. Also the place where I define months doesn’t sound right, as this is part of the while loop, but If I don’t write it there, I get months undefined.

Thanks in advance.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.