-1

i'm beginner. i want user read question from list and enter 1,2,3 or 4 for answer but i have problem when user don't enter number and press enter . ValueError: invalid literal for int() with base 10: ''

print("read question and answer :enter 1 , 2, 3 or 4")
q1=[
   "question1  ",
   "question2  ",
   "question3 ",
   "question4  ",

   ]
ans=[]

for x in range(len(q1)):

  try:
     element=int(input(q1[x]))
     while element not in [1,2,3,4]:
         element=int(input(q1[x]))
     else:
         ans.append(element)
  except ValueError:
    element=int(input(q1[x]))          
print(ans)

please help me.

  • 2
    Just test the input as a string and make the int later: `while element not in ['1','2','3','4']:` and once you have a valid int: `ans.append(int(element))` – Mark Jun 20 '21 at 18:42
  • shouldn't this be right? : `element=q1[int(input()]` – The shape Jun 20 '21 at 18:42
  • No it shouldn't. Your code is unconditionally calling `int()` on a string over which you have no control, and if that string can't be interpreted as an integer your program will fail. If your user hits enter then the string is `""` and that is not a valid integer. Perhaps you are expecting `int()` to return zero in that case. It doesn't. – BoarGules Jun 20 '21 at 20:41

1 Answers1

0

read this answer to similar question.

The issus is with your exception handling code, since once an exception/error occurs you are calling int & input again. Please read how to handle exception before using them, as once uou understand that you would be able to debug/fix errors on your own. You can read about exception handling here.

Basically, update your code by removing element=int(input(q1[x])) and adding probably a print statement, asking user to enter/choose a right input after: except ValueError:

gmatharu
  • 83
  • 1
  • 8