0

Could someone explain following results? In first case output is: '5 4 3 2 1' In second: '1 2 3 4 5' I don't understand it because I thought it use stack with LIFO (last in — first out). And result should be '1 2 3 4 5' regardless of position "print" function. I used PyCharm 2021.3.2 (Community Edition).

def pr(n):
    if n >= 1:
        print(n)   # 1'st case
        pr(n - 1)
        # print(n)  # 2'nd case


a = int(input())
pr(a)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Oleg
  • 3
  • 2
  • 2
    In the first case you are printing on your way down the call stack. In the second casse you are printing on the way back up. – John Coleman Nov 30 '22 at 21:59
  • 2
    It's very simple: in the 1st case, the value is printed BEFORE going deeper, so first 5 in the 1st call, 4 in the 2nd call... ; in the 2nd case, the value is printed AFTER going deeper, so it's actually printed when the script "goes up" from the recursion. – Swifty Nov 30 '22 at 21:59
  • 1
    You can see step by step execution [here](https://pythontutor.com/render.html#code=def%20pr%28n%29%3A%0A%20%20%20%20if%20n%20%3E%3D%201%3A%0A%20%20%20%20%20%20%20%20print%28n%29%20%20%20%23%201'st%20case%0A%20%20%20%20%20%20%20%20pr%28n%20-%201%29%0A%20%20%20%20%20%20%20%20%23%20print%28n%29%20%20%23%202'nd%20case%0A%0A%0Aa%20%3D%20int%28input%28%29%29%0Apr%28a%29&cumulative=false&curInstr=14&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%225%22%5D&textReferences=false) – ayhan Nov 30 '22 at 22:01
  • 2
    It might be clearer if you do both cases at the same time. Output: '5 4 3 2 1 1 2 3 4 5' – wjandrea Nov 30 '22 at 22:06
  • Related: [python recursive function that prints from 0 to n?](/q/17127355/4518341) – wjandrea Nov 30 '22 at 22:26

0 Answers0