繁体   English   中英

多条件输入验证

[英]Input validation with multiple conditions

我正在用 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
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而不是if ( https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-伊贝尔/ )。 此外,请考虑提供一些用户反馈(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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM