0

I'm very new to Python and I wrote this part of code where the user must choose between 3 values options. I'm able to check if user insert a value which is less then zero or higher then max but I'm not able to check if user insert no value.

user.choose_action()
choice = input("    Choose action:")
while int(choice) < 1 or int(choice) > 3:
    print("    " + "The choice must be between 1 and 3. Retry.")
    choice = input("    Choose action:")
index = int(choice) - 1
if index == 0:
    other things

This code throws while int(choice) < 1 or int(choice) > 3: ValueError: invalid literal for int() with base 10: ' ' and as far as I understood this error is thrown because I'm trying to convert an empty value to int. I tried to fix with different solutions, for example:

while int(choice) < 1 or int(choice) > 3 or choice == '' :
     rest of the code

or

try:
    choice = input("    Choose action:")
except SyntaxError:
    y = None

or

while int(choice) < 1 or int(choice) > 3 or choice is None :

but nothing seems to work! I know that probably this is very stupid to fix but I'm not able to understand why at moment! What am I doing wrong?

A1010
  • 360
  • 5
  • 18
NoProg
  • 147
  • 2
  • 14
  • 1
    You cannot catch `SyntaxError`, if you are getting those, fix them – C.Nivs May 14 '19 at 14:36
  • Can you please provide a full [mcve] ? – bracco23 May 14 '19 at 14:38
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – quamrana May 14 '19 at 14:42

3 Answers3

3

Change the order of the condition:

while choice == '' or int(choice) < 1 or int(choice) > 3 :
     rest of the code

The difference is that due to short-circuiting, if the input is empty, then it won't try to evaluate the other conditions which would throw an error.

kutschkem
  • 7,826
  • 3
  • 21
  • 56
0

You can use try-except block in this case.try something like this:

while():

   try:
      # your main code here
  except ValueError:
     print('please enter a value:)
     choice=input()

Tojra
  • 673
  • 5
  • 20
0

Please use this

raw_input("Choose action:")
Wang Liang
  • 4,244
  • 6
  • 22
  • 45