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.

user3495234
  • 147
  • 1
  • 2
  • 10
  • 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. – swstephe Oct 26 '14 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? – user3495234 Oct 26 '14 at 17:04
  • value = input("Please enter an integer"); if value: user = int(value) – swstephe Oct 30 '14 at 02:23

1 Answers1

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")
Community
  • 1
  • 1
Christophe Weis
  • 2,518
  • 4
  • 28
  • 32
  • 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? – user3495234 Oct 26 '14 at 17:29
  • Have a look at this question: http://stackoverflow.com/questions/21388541/how-do-you-check-if-a-string-contains-only-numbers-python I updated my answer. If this answers your question, please mark my answer as accepted. – Christophe Weis Oct 26 '14 at 17:39