NoProg
NoProg

Reputation: 145

How to avoid empty input

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?

Upvotes: 0

Views: 3049

Answers (3)

Wang Liang
Wang Liang

Reputation: 4434

Please use this

raw_input("Choose action:")

Upvotes: 0

kutschkem
kutschkem

Reputation: 8163

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.

Upvotes: 3

Tojra
Tojra

Reputation: 683

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

Upvotes: 0

Related Questions