简体   繁体   中英

Loop Flow when using recursion in python

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

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.

在n == 1 return语句的情况下使用print语句,则仅在n = 3和n = 2的情况下(在您的示例中)打印after语句。对于n = 1,将不打印该语句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM