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

In problem set 1, part b, what is the reasoning behind having "balance = initialBalance" appear both in "#Initialize state variables" and after the while statement?

OpenStudy (e.mccormick):

Can you paste the code?

OpenStudy (anonymous):

# Retrieve input initialBalance = float(raw_input("Enter the outstanding balance on your credit card: ")) interestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: ")) # Initialize state variables monthlyPayment = 0 monthlyInterestRate = interestRate/12 balance = initialBalance # Test increasing amounts of monthlyPayment in increments of $100 # until it can be paid off in a year while balance > 0: monthlyPayment += 10 balance = initialBalance numMonths = 0 # Simulate passage of time until outstanding balance is paid off # Each iteration represents 1 month while numMonths < 12 and balance > 0: # Count this as a new month numMonths += 1 # Interest for the month interest = monthlyInterestRate * balance # Subtract monthly payment from outstanding balance balance -= monthlyPayment # Add interest balance += interest # Round final balance to 2 decimal places balance = round(balance,2) print "RESULT" print "Monthly payment to pay off debt in 1 year:", monthlyPayment print "Number of months needed:", numMonths print "Balance:",balance

OpenStudy (e.mccormick):

# Test increasing amounts of monthlyPayment in increments of $100 # until it can be paid off in a year There is the answer. They are doing this more than once.

OpenStudy (anonymous):

So since it is a loop the variable needs to be redefined each time it reenters the loop?

OpenStudy (e.mccormick):

By generating the variables outside the loop, they have a larger scope. If you initialize a variable inside a loop, it only exists inside the loop. By doing it outside the loop, it has a more global scope. That is the reason for the first one. The other is in the loop and resets it each time.

OpenStudy (anonymous):

Ok that makes since, thank you!

OpenStudy (e.mccormick):

np. have fun!

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!