Проверка ввода и проверка, находится ли он в диапазоне - PullRequest
0 голосов
/ 26 сентября 2018
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 голосов
/ 26 сентября 2018

или просто так:

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 строки '1', '2', '3' нет даже необходимости ловить ValueError при приведении к int.

0 голосов
/ 26 сентября 2018

Попробуйте это:

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()
0 голосов
/ 26 сентября 2018

Используйте 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       
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...