发布时间:2022-11-17 文章分类:编程知识 投稿人:李佳 字号: 默认 | | 超大 打印

数据校验的的专业工作请看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