【问题标题】:For loop/Functions Logical Error in Displaying ValuesFor循环/函数显示值的逻辑错误
【发布时间】:2016-03-02 14:50:37
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    在您的dispT 函数中,您可以多次调用LeInvest(和LuInvest)函数。但是没有理由他们应该返回不同的值!即使在第一次调用 LeInvest 时(在第 1 年),此函数也可以查看 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)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多