我不确定如何做到这一点,但我试图一遍又一遍地使用函数的返回值,只需向函数传递一个初始值,而不是手动输入新值。在python中这是可能的吗?3是初始值,4是该函数的返回值。我希望能够传入'4‘而不必执行print(test2(4))来获得下一个值,相反,我希望能够通过使用函数之前的返回值来获得3,4,5,6。
def test(n):
return n + 1
def test2(n):
return test(n)
num = 3
while(True):
print(test2(num))
#num = 3
#num = 4 - 1st iteration
#num = 5 - 2nd iteration
#num = 6 - 3rd iteration, and so on..```
发布于 2019-11-13 13:46:14
正如@hymnsfordisco的回答中所提到的,这听起来很像生成器或对象(初始化+状态)。
def test(initial):
x = initial
while True:
yield x
x += 1
nums = test(5)
for v in nums:
print v
if v > 6:
break
给出
5
6
7
如果你希望它作为一个函数而不是一个循环:
func = test(5).next
func() # -> 5
func() # -> 6
func() # -> 7
发布于 2019-11-13 13:43:09
这就是它!多亏了Seb。我还是不能百分之百确定它是怎么工作的。python新手!
num = 3
while(True):
num = test2(num)
print(num)
sleep(3)```
https://stackoverflow.com/questions/58830779
复制相似问题