2
def main():
    #Get amount of principal, apr, and # of years from user
    princ = eval(input("Please enter the amount of principal in dollars "))
    apr = eval(input("Please enter the annual interest rate percentage "))
    years = eval(input("Please enter the number of years to maturity "))

    #Convert apr to a decimal
    decapr = apr / 100

    #Use definite loop to calculate future value
    for i in range(years):
        princ = princ * (1 + decapr)
        print('{0:5d} {0:5d}'.format(years, princ))

I'm trying to print the years and the principal value in a table, but when I print all that comes out is two columns of 10.

1
  • 2
    You have three places where user input is requested. What input are you providing when your problem occurs? Commented Nov 9, 2015 at 0:42

1 Answer 1

2

So you have several problems. The first problem is a display issue.

Your output statement print('{0:5d} {0:5d}'.format(years, princ)) has several issues.

  1. printing years instead of i, so it's always the same value instead of incrementing
  2. the 0 in the format statement{0:5d} means the 0'th element out of the following values, so you're actually printing years twice, the second one should be 1 instead of 0
  3. you're using d to print what should be a floating point value, d is for printing integers, you should be using something along the lines of {1:.2f} which means "print this number with 2 decimal places

Once you've corrected those you'll still see incorrect answers because of a more subtle problem. You're performing division with integer values rather than floating point numbers, this means that any decimal remainders are truncated, so apr / 100 will evaluate to 0 for any reasonable apr.

You can fix this problem by correcting your input. (As a side note, running eval on user input is usually an incredibly dangerous idea, since it will execute any code that is entered.) Instead of eval, use float and int to specify what types of values the input should be converted to.

The following is corrected code which implements the above fixes.

#Get amount of principal, apr, and # of years from user
princ = float(input("Please enter the amount of principal in dollars "))
apr = float(input("Please enter the annual interest rate percentage "))
years = int(input("Please enter the number of years to maturity "))

#Convert apr to a decimal
decapr = apr / 100

#Use definite loop to calculate future value
for i in range(years):
    princ = princ * (1 + decapr)
    print('{0} {1:.2f}'.format(i, princ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.