How do I check if a user left the 'input' or 'raw_input' prompt empty?

旧街凉风 提交于 2019-11-30 15:15:34

问题


How do I check if input has been entered?

For example:

x = str(raw_input('Message>> '))

or

y = input('Number>> ')

回答1:


You know if nothing was entered for the second one because it will raise a SyntaxError. You can catch the error like this:

try:
    y=input('Number>> ')
except SyntaxError:
    y = None

then test

# not just 'if y:' because 0 evaluates to False!
if y is None:

or, preferably, use raw_input:

try:
    y = int(raw_input('Number>> '))
except ValueError:
    print "That wasn't a number!"

For the first one, x will be an empty string if nothing is entered. The call to str is unnecessary -- raw_input already returns a string. Empty strings can be tested for explicitly:

if x == '':

or implicitly:

if x:

because the only False string is and empty string.




回答2:


This also work too

y = input('Number>> ')
while not y:
    y = input('Number>> ')


来源:https://stackoverflow.com/questions/9914061/how-do-i-check-if-a-user-left-the-input-or-raw-input-prompt-empty

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