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?
Can you paste the code?
# 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
# 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.
So since it is a loop the variable needs to be redefined each time it reenters the loop?
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.
Ok that makes since, thank you!
np. have fun!
Join our real-time social learning platform and learn together with your friends!