验证输入并检查它是否在范围内

时间:2018-09-26 06:58:58

标签: python python-3.x validation

print("What would you like to do:\n1. Enter new information\n2. House- 
based statsitics\n3. Specific Criteria statistics")

while True:
  try:
    option = input("Enter 1 2 or 3: ")
  except ValueError:
    option = input("Enter 1 2 or 3: ")

  if option < 1 and option > 3:
    option = input("Enter 1 2 or 3: ")
  else:
     break

print(option)

我试图确保我的输入介于1到3之间,执行此操作时会收到TypeError,但是如果将其更改为int(option = input("Enter 1 2 or 3: ")),则在输入字符串时将返回错误

3 个答案:

答案 0 :(得分:2)

或者仅仅是:

> google.api_core.exceptions.FailedPrecondition: 400 no matching index
> found. recommended index is:
> - kind: <kind_name>  properties:
>   - name: attr_1
>   - name: attr_2
>   - name: attr_3

由于限制了3个字符串option = None while option not in {'1', '2', '3'}: # or: while option not in set('123') option = input("Enter 1 2 or 3: ") option = int(option) ,甚至在转换为'1', '2', '3'时也不需要捕获ValueError

答案 1 :(得分:1)

尝试一下:

def func():

    option = int(input("enter input"))
    if not abs(option) in range(1,4):
        print('Wrong')
        sys.exit(0)
    else:
        print("Correct")
        func()
func()

答案 2 :(得分:0)

使用range检查输入是否在指定范围内:

print("What would you like to do:\n1. Enter new information\n2. House- based statsitics\n3. Specific Criteria statistics")

while True:
  try:
    option = int(input("Enter 1 2 or 3: "))
  except ValueError:
    option = int(input("Enter 1 2 or 3: "))

  if option in range(1, 4):
    break

print(option)

样品运行

What would you like to do:
1. Enter new information                                    
2. House- based statsitics                                  
3. Specific Criteria statistics                              
Enter 1 2 or 3: 0                                           
Enter 1 2 or 3: 4                                           
Enter 1 2 or 3: a                                           
Enter 1 2 or 3: 2                                           
2