数据校验的的专业工作请看pydantic

 1 from pydantic import BaseModel, conint, ValidationError
 2 
 3 
 4 class NumVerify(BaseModel):
 5     # 限定范围
 6     expected_number: conint(ge=0, le=100)
 7 
 8 
 9 def input_number():
10     while True:
11         number = input(">>请输入:")
12         try:
13             number_input = NumVerify(expected_number=number)
14         except ValidationError as e:
15             print(e)
16             continue
17         else:
18             number = number_input.expected_number
19             break
20     print(">>your number is {}".format(number))
21 
22 
23 if __name__ == '__main__':
24     input_number()

output: 

  >>请输入:-89
  1 validation error for NumVerify
  expected_number
  ensure this value is greater than or equal to 0 (type=value_error.number.not_ge; limit_value=0)
  >>请输入:101
  1 validation error for NumVerify
  expected_number
  ensure this value is less than or equal to 100 (type=value_error.number.not_le; limit_value=100)
  >>请输入:10
  >>your number is 10

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。