簡體   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