Как печатать результаты на python за каждый год до запрошенного года

#python

Вопрос:

У меня есть рабочий код, у меня есть рабочий код, который дает правильный ответ, однако я не могу понять, как заставить его печатать сумму за каждый год (например, если я введу 5 лет, он выдаст суммы только за пятый год. Я хочу, чтобы он печатал год 1, 2 ,3, 4 и 5 (результаты печати за каждый год до введенного года).

 InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))

TotalInterestEarned = 0
for i in range(Years):
    InterestEarned = round(InvestAmount*(Rate/100),2)
    EndingBal = round(InvestAmount InterestEarned , 2)


print("Starting Balance: $"  str (InvestAmount))    
print("Ending balance: $" str(EndingBal))
print("Total Interest Earned: $" str(InterestEarned))
 

Ответ №1:

Это тебе поможет

 InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))

TotalInterestEarned = 0
for i in range(Years):
    InterestEarned = round(InvestAmount*(Rate/100),2)
    EndingBal = round(InvestAmount InterestEarned , 2)
    print(f"{i 1} year - Starting Balance: ${InvestAmount}")    
    print(f"{i 1} year - Ending balance: ${EndingBal}")
    print(f"{i 1} year - Total Interest Earned: ${InterestEarned}")
 

Ответ №2:

Измените свой цикл for следующим образом:

 for i in range(Years):
    InterestEarned = round(InvestAmount*(Rate/100),2)
    EndingBal = round(InvestAmount InterestEarned , 2)
    print("Year"   i 1   " Interest Earned: $"   InterestEarned)
    print("Year"   i 1   " Balance: $"   EndingBal)
 

Комментарии:

1. Теперь я получаю ошибку: можно только связать str (не «int») с str

2. Видеорегистратор я забыл на ул.

3. Это дает мне сейчас год, но проценты или сумма не меняются, она остается прежней каждый год, когда она должна увеличиваться?

Ответ №3:

Переместите операторы печати в цикл for и также распечатайте i

     for i in range(Years):
      InterestEarned = round(InvestAmount*(Rate/100),2)
      EndingBal = round(InvestAmount InterestEarned , 2)
      print("Starting Balance: for year "  (i 1) "$" str (InvestAmount))    
      print("Ending balance: for year"  (i 1) "$" str(EndingBal))
      print("Total Interest Earned: for year"  (i 1)
       "$" str(InterestEarned))