0

Help me!! It's not justified (python)

# Accept the inputs
startBalance = float(input("Enter the investment amount: "))
years = int(input("Enter the number of years: "))
rate = int(input("Enter the rate as a %: "))

# Convert the rate to a decimal number
rate = rate / 100

# Initialize the accumulator for the interest
totalInterest = 0.0

# Display the header for the table V.3
print("%4s%18s%10s%16s" % \
      ("Year", "Starting balance",
       "Interest", "Ending balance"))

# f string
# Compute and display the results for each year
for year in range(1, years + 1):
    interest = startBalance * rate
    endBalance = startBalance + interest
    print(f"{year:>4}{startBalance:<18.2f}{interest:>10.2f}{endBalance:>16.2f}")
    startBalance = endBalance
    totalInterest += interest

# Display the totals for the period
print("Ending balance: $%0.2f" % endBalance)
print("Total interest earned: $%0.2f" % totalInterest)




I was trying to align data in a table on the right side of the column. I use f string and formatting type in the variable placeholder but there was no alignment.

I try to run the code on jupyter and VS Code.

accdias
  • 5,160
  • 3
  • 19
  • 31

1 Answers1

2

There is no need to mix different template systems. Just use f-strings:

pv = float(input('Enter the investment amount: '))
years = range(int(input('Enter the number of years: ')))
rate = int(input('Enter the rate as a %: ')) / 100
interests = 0.0

print('Year Starting balance  Interest  Ending balance')

for year in years:
    interest = pv * rate
    fv = pv + interest
    print(f'{year + 1:>4d}{pv:>17.2f}{interest:>10.2f}{fv:>16.2f}')
    pv = fv
    interests += interest

print(f'Ending balance: ${fv:0.2f}')
print(f'Total interest earned: ${interests:0.2f}')

And here is an example of the output:

Enter the investment amount: 200
Enter the number of years: 10
Enter the rate as a %: 15
Year Starting balance  Interest  Ending balance
   1           200.00     30.00          230.00
   2           230.00     34.50          264.50
   3           264.50     39.67          304.18
   4           304.18     45.63          349.80
   5           349.80     52.47          402.27
   6           402.27     60.34          462.61
   7           462.61     69.39          532.00
   8           532.00     79.80          611.80
   9           611.80     91.77          703.58
  10           703.58    105.54          809.11
Ending balance: $809.11
Total interest earned: $609.11
accdias
  • 5,160
  • 3
  • 19
  • 31