Skip to content

Add robust input validation for row and column inputs #2456

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions TIC_TAC_TOE/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,31 @@ def check_winner(board, player):

def is_full(board):
return all(cell != " " for row in board for cell in row)
# A function that validates user input
def get_valid_input(prompt):
while True:
try:
value = int(input(prompt))
if 0 <= value < 3: # Check if the value is within the valid range
return value
else:
print("Invalid input: Enter a number between 0 and 2.")
except ValueError:
print("Invalid input: Please enter an integer.")

def main():
board = [[" " for _ in range(3)] for _ in range(3)]
player = "X"

while True:
print_board(board)
row = int(input(f"Player {player}, enter the row (0, 1, 2): "))
col = int(input(f"Player {player}, enter the column (0, 1, 2): "))
print(f"Player {player}'s turn:")

# Get validated inputs
row = get_valid_input("Enter the row (0, 1, 2): ")
col = get_valid_input("Enter the column (0, 1, 2): ")

if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ":
if board[row][col] == " ":
board[row][col] = player

if check_winner(board, player):
Expand All @@ -40,7 +54,7 @@ def main():

player = "O" if player == "X" else "X"
else:
print("Invalid move. Try again.")
print("Invalid move: That spot is already taken. Try again.")

if __name__ == "__main__":
main()