2016-03-02 49 views
0

我对Python 3.x颇为陌生,在试图以表格格式显示它们时遇到了逻辑错误。For循环/函数显示值中的逻辑错误

#Main Function: 

def main(): 
    LuInvest() 
    LeInvest() 
    dispT() 

#Function 1 

def LeInvest(): 
    for year in range (1,28): 
     LeGain = (100 * .1) 
     LeTotal = (100 + (LeGain * year)) 
    return LeTotal 

#Function 2 

def LuInvest(): 
    for year in range(1,28): 
     LuTotal = (100 * (1 + .05) ** year) 
    return LuTotal 

#Display Function 

def dispT(): 
    print ("Year:\tLeia's Investment\tLuke's Investment") 
    for year in range (1,28): 
     print ('%i\t %.2f\t\t  %.2f' %(year, LeInvest(),LuInvest())) 

什么被显示为:

Year:  Leia's Investment  Luke's Investment 
1    370.00     373.35 
2    370.00     373.35 
3    370.00     373.35 

如果我插入功能1 & 2内的print语句然后从主功能删除dispT(),它会显示所有正确的价值观,多年来,但不是以正确的格式。如果我使用dispT(),它将只显示功能1的最终金额。 2的range(如上所示)。

回答

1

在您的dispT函数中,您可以多次调用LeInvest(和LuInvest)函数。但没有理由为什么他们应该返回不同的价值观!即使在第一次电话(第一年)到LeInvest时,该功能也可以追溯到27年。

LeInvest功能,你可能不希望环路range(1,28),而是通过类似range(1, maxyear),其中maxyear是函数的参数。

例如为:

def LeInvest(maxyear): 
    for year in range (1,maxyear): 
     LeGain = (100 * .1) 
     LeTotal = (100 + (LeGain * year)) 
    return LeTotal 

# TODO: Similar for LuInvest 

def dispT(): 
    print ("Year:\tLeia's Investment\tLuke's Investment") 
    for year in range (1,28): 
     print ('%i\t %.2f\t\t  %.2f' %(year, LeInvest(year),LuInvest(year))) 
+0

它的工作!非常感谢你。 – MikeD