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:
- I do a simple
num = raw_input()
, then check whethernum == ''
. Afterwards, I can cast it to aint
. - I catch a
ValueError
. But in that case, I can't differentiate between an non-numerical input and a empty input.
Any suggestio开发者_StackOverflowns on how to do this?
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
.
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
精彩评论