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

只谈情不闲聊 提交于 2019-12-02 07:07:54

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/19579997/how-to-catch-empty-user-input-using-a-try-and-except-in-python

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