Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 21 Online
OpenStudy (anonymous):

Help needed with P1 Problem 2 - infinite loop in my code...

OpenStudy (anonymous):

Can anyone find where the infinite loop is? I can't seem to locate it! ## Problem Set 1, Problem 2 outstandingBalance = float(raw_input("Please enter the outstanding balance on the card: ")) interestRate = float(raw_input("Please enter the annual interest rate on the card: ")) monthlyInterestRate = interestRate/12.0 paymentAmount = 10 monthsRequired = 1 while paymentAmount<=outstandingBalance: while monthsRequired<=12 and outstandingBalance>0: outstandingBalance = outstandingBalance * (1+monthlyInterestRate)-paymentAmount monthsRequired = monthsRequired +1 paymentAmount = paymentAmount+10 print ("Monthly payment to pay off debt in 1 year: " + str(paymentAmount)) print ("Number of months needed: " + str(monthsRequired)) print ("Balance: " + str(outstandingBalance))

OpenStudy (espex):

I believe your problem lies here: while paymentAmount<=outstandingBalance: while monthsRequired<=12 and outstandingBalance>0: I put in 1000 and .1 and stepped through the sequence 12 times. On the 12th run your values are: paymentAmount: 120 outstandingBalance: 416.901495833 monthsRequired: 12 As you can see, the paymentAmount is still less than the outstandingBalance, the outer loop is true, however the months required are about to be greater than 12 and thus the inner loop is false. This causes the infinite loop because it is never able to break out of both while loops.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!