while True:
This is never great and should indicate to you that there is a better way to design this code. Even if it is just using boolean flag.
if len(player_choice) != 2:
continue
if not player_choice[0].isdigit() or not player_choice[0].isdigit():
So aside from the obvious typo where the second clause should have been player_choice[1]
, in python it is more idiomatic to try
instead of if
(https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/). Also, consider providing some user feedback as to (a) the fact that the command failed and (b) why it failed:
try:
row = int(player_choice[0])
col = int(player_choice[1])
except ValueError:
print(f"Input must be two numbers, however non-digit characters were received."
except IndexError:
print("The input should be two numbers separated by a space but no space was entered")
For validating the limits, again consider offering some feedback. Also ROWS
etc are not such descriptive names. num_rows
is better. Also, instead of a constant, rather make this whole thing a function and set these as default arguments instead;
def validate_user_input(player_choice: str, num_rows: int = 10, num_cols: int = 10) -> bool:
try:
row, col = player_choice.split()
except ValueError:
print("Bad input: The input should be exactly two numbers separated by a space.")
return False
try:
row = int(row)
col = int(col)
except ValueError:
print(f"Input must be two numbers, however non-digit characters were received."
return False
if row < 0 or row > num_rows:
print(f"The first number must be between 0 and {num_rows} but {row} was passed.")
return False
if col < 0 or col > num_rows:
print(f"The second number must be between 0 and {num_cols} but {col} was passed.")
return False
return true
And then your loop becomes:
valid_input = False
while not valid_input:
player_choice = input("Enter the row and column of your choice separated by a space: ")
valid_input = validate_user_input(player_choice)