Adam Koch
Adam Koch

Reputation: 9

How to work around integer input within a while loop

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.

Upvotes: 0

Views: 62

Answers (2)

dome
dome

Reputation: 841

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

Upvotes: 1

Dov Rine
Dov Rine

Reputation: 840

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

Upvotes: 0

Related Questions