Home > Mobile >  IndexError in a recursive function inside a Class
IndexError in a recursive function inside a Class

Time:02-08

I am having issues where I want the user to input a number that is 1-9. If they enter a number outside the range, I want them to get a message "Please enter a valid number" and to be able to enter another number. If they enter say "145" it will ask them to enter a valid number just like I want (yay!). Then when they enter, lets say "4", an IndexError: list out of range pops up. self.board is a list with 9 elements.

My thought is that python still trying to use the first number, but if I print the number before IndexError line, it shows the correct number, '4'. Any help is appreciated!

Here is my code:

    self.board=[
        " "," "," ",
        " "," "," ",
        " "," "," "
    ]
def turn(self, player):
   result=int(input("Choose your next move \n"))
   if result < 1 or result>9:
        print("Please enter a valid number (1-9)")
        self.turn(player)

   if self.board[result-1] == " ":
        self.board[result-1] = player
   else:
        print("This spot has already been chosen. Please choose another place for your next move")
        self.turn(player)

CodePudding user response:

The problem here is that your method is recursive and execution continues after your recursion collapses. You have two if statements in a row. When the first one is true, it recurses but when that recursed call finishes it continues execution with the bad input. You need to make the second if statement an elif instead. That way after your recursed function call finishes nothing else is executed.

Try this instead:

    self.board=[
        " "," "," ",
        " "," "," ",
        " "," "," "
    ]
def turn(self, player):
   result=int(input("Choose your next move \n"))
   if result < 1 or result>9:
        print("Please enter a valid number (1-9)")
        self.turn(player)

   elif self.board[result-1] == " ":
        self.board[result-1] = player
   else:
        print("This spot has already been chosen. Please choose another place for your next move")
        self.turn(player)
  •  Tags:  
  • Related