0

I'm having concerns on how the loop flow works in Python when Recursion is used (never mind the function, just learning about loop flow)

def factorial(n):
    print("first line")
    if n == 1 or n == 0:
        return 1

    result = n * factorial(n-1)
    print('line after result')
    print('current result is ' + str(result) )
    print('before return result')
    return result

In my example I used factorial(3) and I'm getting it like this:

first line
first line
first line
line after result
current result is 2
before return result
line after result
current result is 6
before return result
6

How come I get line after result three times after result is computed/returned. Am I not supposed to get it only once after the result? How many times does the loop return the result? I don't understand how recursion loop flow works in python. Please help. Thanks

0

2 Answers 2

1

You have line after result 2 times(not 3). This line is printed for each return during the recursion calls.

  1. You call factorial(3). Python prints "first line" and runs a function factorial(2).
  2. Python prints "first line" and calls factorial(1).
  3. Python prints "first line" and returns 1;
  4. Gets result from the step 3 and prints line after result;
  5. Gets result from the step 2 and prints line after result;
  6. Gets result from the step 1.
Sign up to request clarification or add additional context in comments.

Comments

0

With the print statement after the case where n==1 return statement, then the print after will only be printed (in your example) for n = 3, and n = 2. For n = 1 the statement will not be printed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.