Sebastian
Sebastian

Reputation: 57

Why do I keep getting the maximum recursion depth exceeded error?

I'm writing code for a number guessing game and it has to be sold by recursion. But when I execute it I get this error: maximum recursion depth exceeded. Why is that?

This is my code:

import random
n = random.randrange(0,100)
guess = int(input("Introduce a number: "))
def game(guess):
    if guess == n:
        print("Your guess is correct.")
    elif guess > n:
        print("Your guess is too high")
        game(guess)
    elif guess < n:
        print("Your guess is too low")
        game(guess)
game(guess)

Upvotes: 0

Views: 1414

Answers (4)

Srikanth Lankapalli
Srikanth Lankapalli

Reputation: 136

maximum recursion depth exceeded occurs because of the infinite loops when guess > n , guess < n condition is meet. To know further refer to this question.

The below code should work as expected.

import random,sys
n = random.randrange(0,100)

def game(guess):
    if guess == n:
        print("Your guess is correct.")
        sys.exit()
    elif guess > n:
        print("Your guess is too high")
    elif guess < n:
        print("Your guess is too low")

while True:
    guess = int(input("Introduce a number: "))
    game(guess)

Upvotes: 0

Remi Guan
Remi Guan

Reputation: 22282

  1. You need use random.randint() function like this: n = random.randint(0, 100).
  2. Use a while loop is recommended.
  3. You didn't call guess = int(input("Introduce a number: ")) again.

import random
n = random.randint(0, 100)
guess = int(input("Introduce a number: "))

def game(guess):
    while guess != n:
        if guess > n:
            print("Your guess is too high")
        elif guess < n:
            print("Your guess is too low")
        guess = int(input("Introduce a number: "))

    else:
        print("Your guess is correct.")

game(guess)

Upvotes: 0

mertyildiran
mertyildiran

Reputation: 6613

Your game function don't need any parameter. You need to use else instead of last elif and guess = int(input("Introduce a number: ")) step should be in your game function (Tested):

import random
n = random.randrange(0,100)
def game():
    guess = int(input("Introduce a number: "))
    if guess == n:
        print("Your guess is correct.")
    elif guess > n:
        print("Your guess is too high")
        game()
    else:
        print("Your guess is too low")
        game()
game()

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

The reason is that, unless guess is equal to n the first time you call the function, you have an infinite recursion because you call game with the same value of guess. You don't provide any way to stop the recursion.

Upvotes: 1

Related Questions