具有多个条件的输入验证

时间:2019-07-11 12:15:13

标签: python validation

我正在用Python编写一个简单的游戏,用户输入由rowcolumn定义的矩阵元素,并用空格分隔。我想验证此输入。

我想我已经用下面的代码正确地解决了这个问题,但是我很好奇我的方法是否是一种好的方法,或者我是否可以做出明显的改进或逻辑上的错误。

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

1 个答案:

答案 0 :(得分:1)

while True:

这从来都不是一件好事,应该向您表明,有一种更好的方法来设计此代码。即使只是使用布尔标志。

if len(player_choice) != 2:
    continue
if not player_choice[0].isdigit() or not player_choice[0].isdigit():

因此,除了明显的拼写错误(第二个子句应该是player_choice[1]之外)之外,在python中,try而不是ifhttps://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/)更惯用。另外,请考虑提供有关(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")

要验证限制,请再次考虑提供一些反馈。同样,ROWS等也不是此类描述性名称。 num_rows更好。另外,除了将其作为常量之外,还可以将其作为一个函数并将其设置为默认参数;

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

然后您的循环变为:

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)