Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I check if input has been entered?

For example (python2)

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

or (python3)

y = input('Number>> ')
like image 379
IT Ninja Avatar asked Mar 28 '12 19:03

IT Ninja


2 Answers

This also work too

y = input('Number>> ')
while not y:
    y = input('Number>> ')
like image 92
code-8 Avatar answered Nov 20 '22 06:11

code-8


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 an empty string.

like image 38
agf Avatar answered Nov 20 '22 06:11

agf