0

I was attempting to distinguish an empty input from others using the try catch statement. Currently, I have this.

while True:
    try:
        user = int(input("Please enter an integer"))
        break
    except ValueError:
        print("Must be an integer")

The problem comes from the fact that I would like a separate error statement if the user does not enter anything and only presses the enter key. However, it still reads that particular input as a ValueError and gives the me the message above no matter what else I try.

3
  • You could just check the input before passing to int. If you want a one-liner, you could also do: int(input("Please enter an integer") + 1/0). That will raise ZeroDivisionError if empty string. Commented Oct 26, 2014 at 16:57
  • I'm sorry. I'm a little new to this. How would I check the input before I pass it to int? Commented Oct 26, 2014 at 17:04
  • value = input("Please enter an integer"); if value: user = int(value) Commented Oct 30, 2014 at 2:23

1 Answer 1

1

You can test if the string is not empty.

while True:
    try:
        s = input("Please enter an integer")
        if not s:
             print ("Input must not be empty")
        elif not s.isdigit():
             print ("Input must be a digit")
        else:
            user = int(s)
            break
    except ValueError:
        print("Must be an integer")
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It looks like that works. Though if you don't mind, I had a related question. What if you wanted the user to enter a string such as a letter and have the program return an error if the user entered an integer?
Have a look at this question: stackoverflow.com/questions/21388541/… I updated my answer. If this answers your question, please mark my answer as accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.