如何在While循环中处理整数输入

时间:2019-05-26 09:58:14

标签: python python-3.x

该代码可以永久运行,除了index_input == "Q"时。我的问题是因为我在下一行转换为整数,代码失败,并将'Q'识别为整数。

while True:
  index_input = input("Enter index to insert element to list (enter Q to quit): ")
  index_input_int = int(index_input)

  if (index_input == "Q"):
    print('Good bye!')

    break

  elif (index_input_int >= 6):
    print('Index is too high')

  elif (index_input_int <= -1Q):
    print('Index is too low')

预期结果是'Q'将打破while循环。

2 个答案:

答案 0 :(得分:1)

如果您尝试将Q字符或任何其他字符串转换为整数,则会抛出ValueError。您可以使用try-except

while True:
    index_input = input("Enter index to insert element to list (enter Q to quit): ")

    try:
        index_input_int = int(index_input)
    except ValueError:
        if index_input == "Q":
            print('Good bye!')
            break

    if index_input_int >= 6:
        print('Index is too high')
    elif index_input_int <= -1:
        print('Index is too low')

答案 1 :(得分:0)

只需在检查“ Q”之后将演员表移至int并将其他所有内容放入else块中即可:

while True:
  index_input = input(
      "Enter index to insert element to list (enter Q to quit): ")

  if (index_input == "Q"):
    print('Good bye!')
    break

  else:

    index_input_int = int(index_input)
    if (index_input_int >= 6):
        print('Index is too high')

    elif (index_input_int <= -1Q):
        print('Index is too low')