smc
smc

Reputation: 205

How to repeat a function with the values returned by the function itself?

I have this function which returns two values and I want to repeat the same with those returned values.

fPoint = getFirstPoint (x, y, currCalcX, currCalcY) 
newCurrValX, newCurrValY = fPoint
print(newCurrValX, newCurrValY)

Above function returns values like this:

250.0 60.0

I want to apply these values on currCalcX and currCalcY and repeat the function getFirstPoint() until None is returned.

Upvotes: 1

Views: 59

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51683

Use a loop:

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

Output:

3 3
2 2
1 1
0 0
Done

Recursion is not needed here - it stacks up on function stack frames needlessly. You might hit the recursion limit if it takes too many recursions (and it is not needed at all) - see What is the maximum recursion depth in Python, and how to increase it? for recursion limit explanations.

Upvotes: 3

Related Questions