对于 loop/Functions 显示值的逻辑错误
For loop/Functions Logical Error in Displaying Values
我是 Python 3.x 的新手,并且 运行 在尝试以 table 格式显示我的函数时遇到逻辑错误。
#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
(如上所示)。
在您的 dispT
函数中,您多次调用 LeInvest
(和 LuInvest
)函数。但是他们没有理由 return 不同的值!即使在第一次调用 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)))
我是 Python 3.x 的新手,并且 运行 在尝试以 table 格式显示我的函数时遇到逻辑错误。
#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
(如上所示)。
在您的 dispT
函数中,您多次调用 LeInvest
(和 LuInvest
)函数。但是他们没有理由 return 不同的值!即使在第一次调用 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)))