Shakespeareeee
Shakespeareeee

Reputation: 79

How do I add a counter to track the months and years in one while loop?

so I am trying to create a program and I have the program complete for the most part but I am having some trouble with counters. -I need to add a counter for months and years that track how long it will take to become a millionaire. -I have the months counter correct, but I am having trouble trying to figure out the years counter.

Here is my code so far:

balance = float(input("Enter initial amount: "))
monthlyContribution = float(input("Enter monthly contribution: "))
interestRate = float(input("Enter annual interest rate: "))
month = 0
year = 0

while balance < 1000000 :
   month = month + 1
   year = year + 1
   interest = interestRate/100
   balance = balance + monthlyContribution + (balance + monthlyContribution) * interest/12
   print(f'Current Balance: ${balance:,.2f}', (f'after {month} months'), (f' or {year} years'))

print(f'Congratulations, you will be a millionaire in {month} months: ${balance:,.2f}')

Upvotes: 1

Views: 128

Answers (2)

vash_the_stampede
vash_the_stampede

Reputation: 4606

After discussion here is final result:

balance = float(input("Enter initial amount: "))
monthlyContribution = float(input("Enter monthly contribution: "))
interestRate = float(input("Enter annual interest rate: "))
month = 0
interest = interestRate/100

while balance < 1000000 :
    month = month + 1
    balance +=  monthlyContribution + (balance + monthlyContribution) * interest/12
    if not month % 12:
        year = month//12
        rem = month % 12
        print(f'Current Balance: ${balance:,.2f} after {month} or {year} years' +
              f'and {rem} months')

year = month//12
rem = month % 12

print(f'\nCongratulations, you will be a millionaire in {month} months' +
      f' or {year} years and {rem} months' +
      f'\nCurrent Balance: ${balance:,.2f}')

Upvotes: 1

ab15
ab15

Reputation: 373

@vash_the_stampede's answer works. If you wanted to have a whole number of years, you could also increment the counter for year when month is a multiple of 12.

if month >= 12 and month % 12 == 0:
    year += 1

Upvotes: 0

Related Questions