对于显示值的循环/函数逻辑错误

时间:2016-03-02 14:50:37

标签: python function python-3.x for-loop logic

我是Python 3.x的新手,并且在尝试以表格格式显示时遇到了我的函数的逻辑错误。

#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&中插入print语句2然后从主函数中删除dispT(),它将显示多年来的所有正确值,但格式不正确。如果我使用dispT(),它只会显示功能1&的最终金额。 2 range(如上所示)。

1 个答案:

答案 0 :(得分:1)

dispT函数中,您可以多次调用LeInvest(和LuInvest)函数。但他们没有理由回归不同的价值观!即使是第一次致电(第1年)到LeInvest,这个功能也会持续27年。

LeInvest函数中,您可能不想在range(1,28)中循环,而是通过类似range(1, maxyear)的循环,其中maxyear是函数的参数。

E.g:

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)))