How to round this code without getting an error? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: How to round this code without getting an error? (/thread-11255.html) |
How to round this code without getting an error? - wlsa - Jun-30-2018 I first used the following code balance=42 annualInterestRate=.2 monthlyPaymentRate=0.04 month=1 while month <=12: balance=(balance+balance*(annualInterestRate/12))-(monthlyPaymentRate*(balance+balance*(annualInterestRate/12))) print('Month ' +str(month) + ' Remaining balance: '+ str(balance) month+=1I then realized I want the balance in line 9 to round to 2 decimal places so I edited my code to balance=42 annualInterestRate=.2 monthlyPaymentRate=0.04 month=1 while month <=12: balance=(balance+balance*(annualInterestRate/12))-(monthlyPaymentRate*(balance+balance*(annualInterestRate/12))) print('Month ' +str(month) + ' Remaining balance: '+ str(round(balance, 2)) month+=1Note line 9, the only thing I changed was to print the balance as rounded. Python is giving me an error when I try the second posted code, what is wrong with it?? RE: How to round this code without getting an error? - ichabod801 - Jun-30-2018 Please post the full text of the error you are getting. RE: How to round this code without getting an error? - ljmetzger - Jun-30-2018 Please note that both your examples do not run. They both need an extra ) at the end of the print statement (line 9) to run.After correcting the error, your code works, but does not print two decimal places in all instances (output excerpt follows): Try the following new format line:balance = 42 annualInterestRate = .2 monthlyPaymentRate = 0.04 month = 1 while month <= 12: balance = (balance + balance * (annualInterestRate/12)) - (monthlyPaymentRate * (balance + balance * (annualInterestRate / 12))) print('Month {:2} Remaining balance: {:.2f}'.format(month, balance)) month += 1 Now a couple of recommendations to improve your code and make it more pythonic:a. Python variable names are recommended to be all lower case (e.g. annualInterestRate should be annual_interest_rate ).b. Spaces are recommended before and after operators month += 1 .c. A for loop is usually preferred to a while loop. d. Rearranging and simplifying your balance equation For future reference, Python coding rules (and recommendations) are in PEP-8. See https://www.python.org/dev/peps/pep-0008/ balance = 42 annualInterestRate = .2 monthlyPaymentRate = 0.04 #NOTE: range(1, 13) executes 1 thru 12 for month in range(1, 13): balance = (balance + balance * (annualInterestRate/12)) * (1.0 - monthlyPaymentRate) print('Month {:2} Remaining balance: {:.2f}'.format(month, balance))Lewis |