Home > Back-end >  Python Double Function recursion
Python Double Function recursion

Time:05-28

I was working on a pygame project on VS code and accidentally written the following code:

def appear():
    end()

def end():
    appear()

and my pylance shown no error. I was wondering why in line 2 it was not showing "end is not defined".

And when I ran this small piece of code in a seperate python file:

def appear():
    end()

def end():
    appear()

appear()

the interpreter too did not show NameError but instead after four to five seconds it shows a RecursionError, something like this:

...
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
RecursionError: maximum recursion depth exceeded

What does it mean??

CodePudding user response:

In Python, functions must be defined before they are called (executed, not just used in another definition). Therefore, there is no problem with your function definitions. Well, apart from creating an infinite recursion loop... The error the Python interpreter provided ("RecursionError: maximum recursion depth exceeded") when you executed it happens due to the fact that Python allows only certain level of recursion, which I guess is 1000 by default (can be changed) if I remember correctly. As your functions call each other indefinitely, all the possible recursions have been done in those 4 seconds.

  • Related