[英]Input validation with multiple conditions
I'm writing a simple game in Python where the user enters a matrix element defined by row
and column
separated by a space.我正在用 Python 编写一个简单的游戏,其中用户输入一个由空格分隔的
row
和column
定义的矩阵元素。 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/ ).因此,除了第二个子句应该是
player_choice[1]
的明显错字之外,在 python 中, try
而不是if
( https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-伊贝尔/ )。 Also, consider providing some user feedback as to (a) the fact that the command failed and (b) why it failed:此外,请考虑提供一些用户反馈(a)命令失败的事实和(b)失败的原因:
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. ROWS
等也不是这样的描述性名称。 num_rows
is better. num_rows
更好。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.