수신될 때까지 유효한 사용자 입력 요청
사용자 입력을 요청할 때 충돌이 발생하거나 잘못된 값을 수락하는 대신 잘못된 응답을 정상적으로 처리하는 것이 중요합니다. . 다음 기술은 유효한 입력을 얻도록 보장합니다.
예외 입력에 대한 Try/Except
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!