tags:

views:

44

answers:

2

Hi all. 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 whether num == ''. Afterwards, I can cast it to a int.
  • I catch a 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?

+2  A: 

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.

Thomas
Perfect! Thank you!
sukhbir
A: 

From a non-pythoner:

num = your_default_value;  
input = get_input();  
if(input != '') num = parse_integer(input);  
ItzWarty