How to catch empty user input using a try and except in python?

Hugh Craig picture Hugh Craig · Oct 25, 2013 · Viewed 29.6k times · Source

I am trying to figure out how I can catch empty user input using a try and except. If you had this for example:

try:
    #user input here. integer input 
except ValueError:
    #print statement saying empty string.

Although I also need to catch another value error to make sure they entered an integer and not a character or string how could I use an if and elif setup in order to figure out if it is an empty string or str instead of int

Answer

abarnert picture abarnert · Oct 25, 2013

If you literally want to raise an exception only on the empty string, you'll need to do that manually:

try:
    user_input = input() # raw_input in Python 2.x
    if not user_input:
        raise ValueError('empty string')
except ValueError as e:
    print(e)

But that "integer input" part of the comment makes me think what you really want is to raise an exception on anything other than an integer, including but not limited to the empty string.

If so, open up your interactive interpreter and see what happens when you type things like int('2'), int('abc'), int(''), etc., and the answer should be pretty obvious.

But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input() before the try, and check whether user_input is empty within the except. (You put if statements inside except handlers all the time in real code, e.g., to distinguish an OSError with an EINTR errno from one with a different errno.)