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

☆樱花仙子☆ 提交于 2019-12-02 10:13:36

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

try:
    input = raw_input('input: ')
    if int(input):
        ......
except ValueError:
    if not input:
        raise ValueError('empty string')
    else:
        raise ValueError('not int')

try this, both empty string and non-int can be detected. Next time, be specific of the question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!