-4

I have been learning about recursion and decided to write a Python script that would print "Hello" and call itself again, however it keeps on printing "Hello" until Python throws RuntimeError: maximum recursion depth exceeded.

I do not understand recursion very well so if someone could explain it to me and why Python is throwing this error. How does it work and how can I fix it?

def function(): 
    print('Hello') 
    function()
function()
Matthias
  • 12,873
  • 6
  • 42
  • 48
  • 4
    better to add code which you are using for recursion – sahasrara62 Jul 04 '19 at 07:04
  • 1
    "I have been learning about Recursion and decided to write a Python script " and " i do not understand recursion very well so if someone could explain it ". So try to read again about recursion. Also post your code – Wonka Jul 04 '19 at 07:06
  • if you see many "hello" then your recursion works correctly. Because every executed function needs some memory for variables and recursion can execute a lot of functions and use a lot of memory so Python has restriction for number of recursions to not use all memory. – furas Jul 04 '19 at 07:11
  • def Function(): print (' Hello ') Function() – Jeff Smith Jul 04 '19 at 07:17

3 Answers3

0

The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows. Try increasing the recursion limit (sys.setrecursionlimit) or re-writing your code without recursion.

sys.getrecursionlimit()

Return the current value of the recursion limit, the maximum depth of the Python >interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().

Community
  • 1
  • 1
ncica
  • 7,015
  • 1
  • 15
  • 37
0

Recursion is basically a function calling itself. Consider the function that you talked about:

def hellofunc():
   print("Hello world!")
   hellofunc()

Here, the function hellofunc() keeps printing "Hello world!" and calling itself indefinitely as you haven't specified any condition to break out of this. Function calls are stored on the stack. So during recursion, the parent function call is pushed onto the stack everytime another hellofunc() is called. Since you have not specified any limit or condition to break out of this, the maximum number of function calls placed on the stack is exceeded or in other words, the function calls stack reached it's maximum depth. This is called maximum recursion depth. To prevent this, you could do something like:

def hellofunc(x):
   if x <= 0:
      return
   print("Hello world!")
   hellofunc(x-1)

If you do

hellofunc(4)

The output would be:

"Hello world!"
"Hello world!"
"Hello world!"
"Hello world!"

Hope this helps!

Neeru Ezio
  • 63
  • 1
  • 7
0

You can get more information about the RuntimeError here. Regarding recursive functions, read this chapter