Compound interest in Python using "while"

Asked

Viewed 366 times

0

Recently I was trying to solve an exercise to learn Python, but I found big problems when I tried to calculate compound interest. I used the mathematical formula of the amount and simply I have no idea what this wrong (in particular with the 27° line. I believe the problem of logic is there, whatever).

Below is my faulty code:

c = float(input('Digite o depósito inicial: R$'))
i = float(input('Agora, digite a taxa de juros de uma poupança: '))
t = 1   # Contador dos meses
c2 = None
while t <= 24:
    m = c * (1 + (i / 100)) ** t
    if t == 1:
        print(f'\nNo mês {t}, o valor dos juros será igual a R${m:.2f}')
    else:
        print(f'\nNo mês {t}, o valor dos juros será igual a R${m:.2f}')

    if t == 24:
        break

    t = t + 1

    op = input(f'Deseja realizar um depósito para o {t}° mês[S/N]? ').strip().upper()[0]

    while op != 'S' and op != 'N':
        op = input(f'OPÇÃO INVÁLIDA! Deseja realizar um depósito para o {t}° mês[S/N]? ').strip().upper()[0]

    if op == 'S':
        c2 = float(input(f'Digite o valor do depósito do {t}° mês: R$'))

    else:
        c2 = 0
    c = c2 + m

j = c * (1 + (i / 100)) ** t
print(f'No total, a quantidade de reais ganha com os JUROS COMPOSTOS será igual a R${j - c:.2f}')

I sought some references to the solving this problem, especially the blog post of Professor Nilo, author of the book "Introduction to Pyhton Programming - Algorithms and Programming Logic for Beginners", where is this exercise (Being more specific, is the 5.12 of 5° chapter)

IMPORTANT DETAIL: I noticed that, in the link above, the teacher DOES NOT use the conventional mathematical formula of the Amount, but I just don’t understand why

For self-correction, I used several websites, but the main compound interest simulator was this:

  • I couldn’t help but notice that the "punctuation" of my question fell. Please leave suggestions below, so that I can clarify the passages that were confused and improve the understanding of my question

1 answer

3


Let’s forget for a while the lines of code and focus on the logic of the program. Leaving the formulas aside, let’s understand the problem. A monthly compound interest application is nothing more than a principal that is "updated" at the end of each month. To do this "update", a parameter follows that in this case is to add to the value of the previous month an extra value (interest). This extra value is defined by the interest rate multiplied by the value of the previous month (in the case of simple interest, the multiplication would always be by the initial capital). With that in mind, we can forget the formula and think:

initial capital = x | interest rate = 1% a.m.

primeiro mês = capital inicial + (capital inicial * 0.01)

segundo mês = primeiro mês + (primeiro mês * 0.01) + supply (if available)

terceiro mês = segundo mês + (segundo mês * 0.01) + supply (if available)

...

Thus, the program is built without the formula:

capital_inicial = float(input('Digite o depósito inicial: R$'))
i = float(input('Agora, digite a taxa de juros de uma poupança: '))
i = (i/100) # Definindo o valor de i separadamente para deixar o código mais limpo
t = 1   # Contador dos meses
aporte = 0 # Não coloque c2. É muito confuso.

while t < 24:
    if t == 1:
        m = capital_inicial + (capital_inicial * i) # Ou: m = capital_inicial * (1 + i)
        print(f'\nNo mês {t}, o valor dos juros será igual a R${m:.2f}')
    else:
        print(f'\nNo mês {t}, o valor dos juros será igual a R${m:.2f}')

    t = t + 1 # Mesma coisa escrever: t += 1

    op = input(f'Deseja realizar um depósito para o {t}° mês[S/N]? ').strip().upper()[0]
    while op != 'S' and op != 'N':
        op = input(f'OPÇÃO INVÁLIDA! Deseja realizar um depósito para o {t}° mês[S/N]? ').strip().upper()[0]

    if op == 'S':
        aporte = float(input(f'Digite o valor do depósito do {t}° mês: R$'))
    else:
        aporte = 0

    m = m + (m * i) + aporte # Ou: m = m * (1 + i) + aporte

ganho_com_juros = m - capital_inicial # (montante final - capital inicial)
print(f'No total, a quantidade de reais ganha com os JUROS COMPOSTOS será igual a R${ganho_com_juros}')

Some tips:

-> Whenever you have questions like that, forget the code and focus first on logic.

-> From self-explanatory names to their variables. Do not spare in setting the name! This will make you identify the bug faster.

  • His answer was clear, I understood the reasoning. Despite this, I did some tests, especially in the compound interest simulator mentioned in the doubt, and I noticed that the final amount differs from the variable "m" in the program with its final value, although the variation is small. I did a few more tests and I noticed that it was because the simulators on the Internet considered the contribution in the first month, and taking this into account in the program, the difference became even smaller, but it still existed. You would know to answer me why this should happen?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.