Расчет IRA/выхода на пенсию с помощью Python на основе пользовательского ввода

В приведенном ниже коде, хотя и несколько запутанном, пользователю предлагается ввести: количество лет до выхода на пенсию, процентную ставку, начальную сумму и сумму, добавляемую каждый год. Эта часть работает нормально. Сейчас я пытаюсь вычислить значение каждые пять лет на основе ввода пользователя. В основном я хочу, чтобы это выглядело примерно так:

The value of your account after 5 years will be $...
The value of your account after 10 years will be $...
The value of your account after 15 years will be $...
etc... all the way up until the number of years_left is met

Код, который у меня сейчас есть, делает в основном это, за исключением того, что я думаю, что у меня либо математическая ошибка, либо ошибка кодирования (или и то, и другое), которые я не могу понять. Любая помощь будет принята с благодарностью. Мой код ниже:

def main():

    # Number of years left until retirement
    while True:
        try:
            years_left = int(input("Please enter the number of years left until retirement (1-70): "))
        except ValueError:
            print ("Entered value is not a number! Please enter a number 1-70.")
        except KeyboardInterrupt:
            print("Command Error! Please enter a number 1-70.")
        else:
            if 1 <= years_left < 70:
                break
            else:
                print("Entered value is not in the range 1-70.")

    # Interest rate (confirmation needed if greater than 10)
    while True:
        try:
            interest_rate = int(input("Please enter an interest rate: "))
            if interest_rate > 10:
                confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
                if confirm =="y":
                    break
            elif 0 <= interest_rate < 10:
                break
        except ValueError:
            print("Entered value is not a number! ") 

    # Initial amount to the IRA
    while True:
        try:
            initial_amount = int(input("Please enter the initial amount to the IRA: "))
        except ValueError:
            print ("Entered value is not a number! Please enter a number.")
        except KeyboardInterrupt:
            print("Command Error! Please enter a number.")
        else:
            if 0 < initial_amount:
                break
            else:
                print("Entered value is a negative number. Please enter a positive number.")

    # Amount added to the IRA each year
    while True:
        try:
            amount_added = int(input("Please enter the amount added to the IRA each year: "))
        except ValueError:
            print ("Entered value is not a number! Please enter a number.")
        except KeyboardInterrupt:
            print("Command Error! Please enter a number.")
        else:
            if 0 <= amount_added <= 2500:
                break
            else:
                print("Entered amount is not in the range $0 - $2,500.")

    #value = initial_amount + (initial_amount)*interest_rate + amount_added

    value = 0
    for x in range(5, years_left + 5):
        value = initial_amount + (initial_amount) * interest_rate + amount_added
        print("The value of your account after " + str(x) + " years will be $" + str(value))

main()

Моя текущая программа выводит что-то вроде этого:

Please enter the number of years left until retirement (1-70): 10
Please enter an interest rate: 7
Please enter the initial amount to the IRA: 1
Please enter the amount added to the IRA each year: 2000
The value of your account after 5 years will be $2008
The value of your account after 6 years will be $2008
The value of your account after 7 years will be $2008
The value of your account after 8 years will be $2008
The value of your account after 9 years will be $2008
The value of your account after 10 years will be $2008
The value of your account after 11 years will be $2008
The value of your account after 12 years will be $2008
The value of your account after 13 years will be $2008
The value of your account after 14 years will be $2008

person Ben    schedule 07.11.2014    source источник


Ответы (1)


изменить это на:

value = 0
for x in range(5, years_left+5):
    value = initial_amount + (initial_amount) * interest_rate + amount_added
    print("The value of your account after " + str(x) + " years will be $" + str(value))

это:

count=5
value = 0
for x in range(5, years_left):
    value = value + initial_amount + (initial_amount) * interest_rate + amount_added
    print("The value of your account after " + str(count) + " years will be $" + str(value))
    count += 5
    if count > year_left+5:
       break

В вашем случае вы взяли диапазон (5, year_left + 5), он сгенерирует число от 5 до year_left + 5, поэтому оно будет похоже на [5,6,7,8,9.....year_left+5], оно не будет увеличиваться на 5.

более питоническим будет:

for x in range(5, years_left + 5,5):
    value = value + initial_amount + (initial_amount) * interest_rate + amount_added
    print("The value of your account after " + str(x) + " years will be $" + str(value))

он будет увеличиваться на 5

person Hackaholic    schedule 07.11.2014
comment
Это решило бы мою проблему с подсчетом, но все равно каждый раз дает неверные значения. - person Ben; 07.11.2014
comment
теперь проверьте, что вам нужно сделать для значения тоже value = value + your_stufff - person Hackaholic; 07.11.2014
comment
@Ben Надеюсь, это решит вашу проблему, и вы получите концепцию - person Hackaholic; 07.11.2014
comment
Это очень помогает, большое спасибо. Единственное, с чем у меня сейчас проблемы, это остановить его, когда будет достигнуто значение years_left. Например, если ввести 25 для years_left, окончательный вывод даст 5, 10, 15, 20, 25, а затем остановится. - person Ben; 07.11.2014