我有这个返回两个值的函数,我想对这些返回值重复相同的操作。
fPoint = getFirstPoint (x, y, currCalcX, currCalcY)
newCurrValX, newCurrValY = fPoint
print(newCurrValX, newCurrValY)
上面的函数返回值如下:
250.0 60.0
我想将这些值应用于 currCalcX 和 currCalcY 并重复函数 getFirstPoint()
直到返回 None
。
最佳答案
使用循环:
# dummy implementation - returns None if a or b is 0, ignores x and y
def getFirstPoint(x,y,a,b):
if a==0 or b==0:
return None
return a-1,b-1
x, y, currCalcX, currCalcY = 0,0,4,4 # add sensible values here
while True:
fPoint = getFirstPoint (x, y, currCalcX, currCalcY)
if fPoint is None:
print("Done")
break
currCalcX, currCalcY = fPoint
print(currCalcX, currCalcY)
输出:
3 3
2 2
1 1
0 0
Done
这里不需要递归——它不必要地堆积在函数栈帧上。如果需要太多递归(并且根本不需要),您可能会达到递归限制 - 请参阅 What is the maximum recursion depth in Python, and how to increase it?用于递归限制解释。
关于python - 如何使用函数本身返回的值重复函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57835604/