How to check is an input that is meant to be an integer is empty(in python)?

Viewed 62
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
  while True:
    try:
      user_input = int(input(output_message))
      if user_input >= above:
        return int(user_input)
        break
      else:
        print(error_1.format(above))
    except ValueError:
      print(error_2)

As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.

When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".

I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?

Thanks in advance.

2 Answers

You could just break the input and the conversion to int into two steps, like this:

def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
  while True:
    try:
      user_input = input(output_message)
      if not user_input:
         print("Please do not leave this blank")
         continue
      user_input = int(user_input)
      if user_input >= above:
        return int(user_input)
        break
      else:
        print(error_1.format(above))
    except ValueError:
      print(error_2)

You could do something like this :

def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
  while True:
    user_input = input(output_message)
    try:
        user_input = int(user_input)
        if user_input >= above:
            return user_input
            break
        else:
            print(error_1.format(above))
    except ValueError:
        if(not user_input):
            print(error_3)
        else:
            print(error_2)

I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.

Related