Reputation: 131627
Consider this code:
>>> num = int(raw_input('Enter the number > '))
If the user types nothing and presses 'Enter', I want to capture that. (Capture an empty input)
There are two ways of doing it:
num = raw_input()
, then check whether num == ''
. Afterwards, I can cast it to a int
.ValueError
. But in that case, I can't differentiate between an non-numerical input and a empty input.Any suggestions on how to do this?
Upvotes: 3
Views: 9602
Reputation: 98
Something like:
flag = True
while flag:
try:
value = input(message)
except SyntaxError:
value = None
if value is None:
print "Blank value. Enter floating point number"
For blank values with input this can catch the exception and alert the user with the print statement
Upvotes: 0
Reputation: 181745
Something like this?
num = 42 # or whatever default you want to use
while True:
try:
num = int(raw_input('Enter the number > ') or num)
break
except ValueError:
print 'Invalid number; please try again'
This relies on the fact that int()
applied to a number will simply return that number, and that the emtpy string evaluates to False
.
Upvotes: 4