1

I am attempting to create a tic tac toe game, where the user input will be 1 - 9 on the numpad. When the user inputs a number it will check if that corresponding spot in the list is respresented with a space (" "), and if not, it will then replace that spot in the list with an X.

However, I keep getting the following error when the input provided by the user is just them hitting the enter key: if update_board[int(user_input)] == " ": ValueError: invalid literal for int() with base 10: ''

I provided the info on the code for context, but how can I check if user input is them just hitting the enter key? I have attempted to check if user_input == "", but that doesn't work either. I get the same error.

update_board = ["#"," "," "," "," "," "," "," "," "," "]

def player_turn():
    # Take in player's input so it can be added to the display board.
    user_input = input('Choose your position: ')

    if update_board[int(user_input)] == " ":
        valid_input = True
    else:
        valid_input = False

    while not valid_input:
        user_input = input("That is not an option, please try again.\n> ")
        if update_board[int(user_input)] == " ":
             valid_input = True
        else:
             valid_input = False  

    return int(user_input)

player1 = "X"
update_board[(player_turn())] = player1
M.Swift
  • 17
  • 6

2 Answers2

0

If the user doesn't enter a valid integer, int(user_input) will raise this error. The solution here is to either check the user_input value beforehand or more simply to use a try/except block

def get_int(msg):
   while True:
      user_input = input(msg).strip() # get rid of possible whitespaces
      try:
          return int(user_input)
      except ValueError:
          print("Sorry, '{}' is not a valid integer")


def player_turn():
    while True:
        user_input = get_int('Choose your position: ')
        if update_board[user_input] == " ":
            return user_input

        print("That is not an option, please try again.")
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

Try to catch the user input in a try except block

try:
    i = int(user_input)
except:
    valid_input = False
    print('Please choose a number between 1 and 9')
else:
    if update_board[int(user_input)] == " ":
        valid_input = True
    else:
        valid_input = False

And maybe make a function of the whole try...else block so you don't have to write it twice

Treizh
  • 322
  • 5
  • 12