0

Code is meant to run forever except for when index_input == "Q". My problem is because i convert to an integer on the next line, the code fails and recognises the 'Q' as an integer.

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')

Expected result is that 'Q' will break the while loop.

Adam Koch
  • 9
  • 2

2 Answers2

1

If you try to convert the Q character or any other string to integer it will throw a ValueError. You can use 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')
dome
  • 820
  • 7
  • 20
0

Just move the cast to int after the check for "Q" and put everything else in an else block:

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')
Dov Rine
  • 810
  • 6
  • 12
  • BTW, This may be of interest to you: https://stackoverflow.com/questions/24072790/detect-key-press-in-python – Dov Rine May 26 '19 at 10:06