請求有效的使用者輸入直至收到
請求使用者輸入時,優雅地處理無效回應而不是崩潰或接受不正確的值至關重要。以下技術可確保獲得有效的輸入:
嘗試/排除異常輸入
使用 try/ except 擷取無法解析的特定輸入。例如:
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, that's not a valid age.") continue break
附加規則的自訂驗證
有時,可以解析的輸入可能仍然不滿足某些條件。您可以新增自訂驗證邏輯來拒絕特定值:
while True: data = input("Enter a positive number: ") if int(data) < 0: print("Invalid input. Please enter a positive number.") continue break
結合異常處理和自訂驗證
結合這兩種技術來處理無效解析和自訂驗證規則:
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, that's not a valid age.") continue if age < 0: print("Invalid age. Please enter a positive number.") continue break
封裝在函數
要重複使用自定義輸入驗證邏輯,請將其封裝在函數中:
def get_positive_age(): while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, that's not a valid age.") continue if age < 0: print("Invalid age. Please enter a positive number.") continue return age
進階輸入清理
您可以建立一個更通用的輸入函數來處理各種驗證場景:
def get_valid_input(prompt, type_=None, min_=None, max_=None, range_=None): while True: try: value = type_(input(prompt)) except ValueError: print(f"Invalid input type. Expected {type_.__name__}.") continue if max_ is not None and value > max_: print(f"Value must be less than or equal to {max_}.") continue if min_ is not None and value < min_: print(f"Value must be greater than or equal to {min_}.") continue if range_ is not None and value not in range_: template = "Value must be {}." if len(range_) == 1: print(template.format(*range_)) else: expected = " or ".join(( ", ".join(str(x) for x in range_[:-1]), str(range_[-1]) )) print(template.format(expected)) else: return value
此函數可讓您指定使用者輸入的資料類型、範圍和其他限制。
以上是Python中如何確保使用者輸入有效?的詳細內容。更多資訊請關注PHP中文網其他相關文章!