Search code examples
pythonloopsinfinite-loop

I am getting an infinite loop when I run my program. How do I fix it?


Output of the code This is a finance problem I was working on. I have a loop set up but after it displays all of the correct values, it displays all "0" for every variable infinitely. My Python versions is 3.6.7 running on Ubuntu.

I have tried to set it up so the current_balance is greater than the ending_balance but the problem is still there.

price = float(input("Enter initial price: "))
INTEREST_RATE = 0.12 / 12
DOWN_PAYMENT = price * .9
monthly_payment = 0
ending_balance = 0
interest = 0
principal = 0
month = 0

print("%s%18s%10s%11s%9s%13s" % ("Month", "Current Balance", "Interest", "Principal", "Payment", "End Balance"))

month = 1
current_balance = DOWN_PAYMENT
interest = current_balance * INTEREST_RATE
monthly_payment = current_balance * 0.05
principal = monthly_payment - interest
ending_balance = current_balance - principal

while ending_balance > 0:
    print("%d%18.2f%10.2f%11.2f%9.2f%13.2f" % (month, current_balance, interest, principal, monthly_payment, ending_balance))
    month += 1
    current_balance = ending_balance
    interest = current_balance * INTEREST_RATE
    monthly_payment = current_balance * 0.05
    principal = monthly_payment - interest
    ending_balance = current_balance - principal

There are no errors, just an infinite loop. The program should be over once ending_balance = 0.


Solution

  • Floating point is your problem. To end the loop use:

    while ending_balance >= 0.005:
    

    The current balance is always getting smaller, but you only show two decimal digits.