Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 279
Hugh Craig Avatar asked Jun 28 '26 16:06

Hugh Craig


1 Answers

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

like image 67
abarnert Avatar answered Jul 01 '26 04:07

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!