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.

1
  • Check for Q first and then convert. :) Commented May 26, 2019 at 10:00

2 Answers 2

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') 
Sign up to request clarification or add additional context in comments.

1 Comment

ValueError can also occur on the input line if the user just press enter key.
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') 

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.