Home > Software engineering >  Infinite recursion with if statement in Python
Infinite recursion with if statement in Python

Time:11-11

I have this code:

def get_girlfriend():
  res = input("Will you go out with me? ")
  if (res == "y"):
    print("We've done it bois")
    return
  get_girlfriend()

but I keep getting this error:

RecursionError: maximum recursion depth exceeded

Could anyone help?

CodePudding user response:

Default recursion depth in python is 1000, but if you need to increase the depth (Not recommended) by;

import sys
sys.setrecursionlimit(needed_depth)

But if you're trying to run your simple program without any Error, try to capture them and handle or set a base limit for the recursion.

Set a base limit for recursion:

def get_girlfriend(n=0):
    res = input("Will you go out with me? ")
    if (n < 100 and res == "y"):
        print("We've done it bois")
        return
    get_girlfriend(n 1)

Try and Capture the Error:

def get_girlfriend():
    res = input("Will you go out with me? ")
    if (res == "y"):
        print("We've done it bois")
        return
    try:
        get_girlfriend()
    except RecursionError:
        return

A Function should always have an exit gateway.

CodePudding user response:

The default maximum recursion depth for python is 1000.

So when the function calls itself to 1000 times, you get the error. I do not know what you aim to achieve by your code but by adding some condition if the statement satisfies your condition, you will be able to terminate.

CodePudding user response:

def get_girlfriend():
    res = input("Will you go out with me? ")
    answer = res
    if (answer == "y"):
        print("We've done it bois")

get_girlfriend()

idk if this what you mean. But here's the output if you type y

Will you go out with me? y We've done it bois

and others but y: Will you go out with me? n

  • Related