11

How do I check if input has been entered?

For example (python2)

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

or (python3)

y = input('Number>> ')
1
  • 1
    The input function won't return until something has been entered. Do you mean how to check if the entered input is empty? Commented Mar 28, 2012 at 19:09

2 Answers 2

27

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@hochl If just spaces aren't a valid message :)
Perfect! Thank you so much for your answer agf and hochl. :)
What about if not x: or if len(x) < 1: as alternatives to if x == '':, or are those considered bad practice?
@Dennis See the last code in my post. I do mention using just if x: to test emptyness.
1

This also work too

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

1 Comment

Simple, self-explanatory 3 line answers are much more preferred. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.