I'm writing a simple game in Python where the user enters a matrix element defined by row
and column
separated by a space. I want to validate this input.
I think I have solved it correctly with the code below, but I'm curious if my approach is a good one, or if there are obvious improvements I could make or errors in my logic please.
player_choice = ["",""]
while True:
player_choice = input("Enter the row and column of your choice separated by a space: ").split(" ")
if len(player_choice) != 2:
continue
if not player_choice[0].isdigit() or not player_choice[1].isdigit():
continue
if int(player_choice[0]) <= 0 or int(player_choice[0]) > ROWS:
continue
if int(player_choice[1]) <= 0 or int(player_choice[1]) > COLUMNS:
continue
else:
break
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.