user225312
user225312

Reputation: 131627

Checking for empty number as input

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:

Any suggestions on how to do this?

Upvotes: 3

Views: 9602

Answers (2)

Suraj N
Suraj N

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

Thomas
Thomas

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

Related Questions