I am a beginner in python and finished learning functions and classes so tried to make a tic tac toe with the help of udemy and using pycharm. My function(player_choice(board)) asks the user which position they want to put the 'x' or 'o' in. It works perfectly if entered a valid position though if enter a non integer answer then it results in an error as my other function(space_check(board, position)) which checks if the space is available or not has the parameter to only accept integer.
def space_check(board, position):
return board[position] == ' '
def player_choice(board):
position = 0
possible_positions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
while position not in possible_positions or not space_check(board, position):
position = input('Choose a position (1-9): ')
return int(position)
This is the output if I enter a string
Choose a position (1-9): e
Traceback (most recent call last):
File "C:\Users\nitin\PycharmProjects\Tkinter1\main.py", line 102, in <module>
position = player_choice(the_board)
File "C:\Users\nitin\PycharmProjects\Tkinter1\main.py", line 65, in player_choice
position = int(input('Choose a position (1-9): '))
ValueError: invalid literal for int() with base 10: 'e'
I have even tried the (try) and (except) methods but still showed the same result. Please tell on how I can code it so that it doesn't result in an error and just asks the user again for the position. Interpreter: Python 3.10