首页 > 解决方案 > 验证输入并检查它是否在一个范围内

问题描述

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: "))它会在输入字符串时返回错误。

标签: pythonpython-3.xvalidation

解决方案


或者只是:

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)

由于对 3 个字符串的限制,在转换为 a 时'1', '2', '3'甚至不需要捕获 a 。ValueErrorint


推荐阅读