return value not matching loop

44 Views Asked by At

my code is split into two pydev files. Functions.py and t12.py. My problem is that when I call the function and the for loop runs, the final value of the loop and the value I call from the t12 function do not match. I am assuming that the loop is running an additional time which is why my answer is different

functions

def gic(value, years, rate):

    print(f"\n{'Year':<2}{'Value $':>10s}")
    print("--------------")
    
    final_value = value
    
    for x in range(years + 1):
        print(f"{x:>2}{final_value:>12,.2f}")
        final_value *= (1 + (rate / 100))
        
    return final_value

t12

# Imports  
from functions import gic

# Inputs 
value = int(input("Value: "))
years = int(input("Years: "))
rate = float(input("Rate: "))

# Function calls
final_value = gic(value, years, rate)

print(f"\nFinal value: {final_value:.2f}")

Code ouput With values (1000,10,5):

Value: 1000
Years: 10
Rate: 5

Year   Value $
--------------
 0    1,000.00
 1    1,050.00
 2    1,102.50
 3    1,157.62
 4    1,215.51
 5    1,276.28
 6    1,340.10
 7    1,407.10
 8    1,477.46
 9    1,551.33
10    1,628.89

Final value: 1710.34

Desired output :

Value: 1000
Years: 10
Rate: 5

Year   Value $
--------------
 0    1,000.00
 1    1,050.00
 2    1,102.50
 3    1,157.62
 4    1,215.51
 5    1,276.28
 6    1,340.10
 7    1,407.10
 8    1,477.46
 9    1,551.33
10    1,628.89

Final value: 1628.89
1

There are 1 best solutions below

0
DarkFranX On

Like John said in a comment, you need to rework the printing orchestration:

def gic(value, years, rate):

    print(f"\n{'Year':<2}{'Value $':>10s}")
    print("--------------")

    final_value = value

    print(f"{0:>2}{final_value:>12,.2f}")
    
    for x in range(years):
        final_value *= (1 + (rate / 100))
        print(f"{x+1:>2}{final_value:>12,.2f}")
    
    return final_value

You want to print after the value was modified. To do so, add an initial print() for the initial value, then reverse the order of operations in the for..loop. Take care to reduce the loop count by 1 and offset the index by +1 inside the loop.