Checking an empty input number

Consider this code:

>>> num = int(raw_input('Enter the number > '))

If the user does not type anything and presses 'Enter', I want to capture it. (Record the empty input)

There are two ways to do this:

  • I make it simple num = raw_input()and then check if there is any num == ''. Subsequently, I can apply it to int.
  • I will catch ValueError. But in this case, I cannot distinguish between non-numeric input and empty input.

Any suggestions on how to do this?

+3
source share
3 answers

Something like that?

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'

It depends on what int(), applied to the number, just returns that number and that the emtpy string evaluates to False.

+4
source

From non-pythoner:

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

- :

flag = True
while flag:
    try:
       value = input(message)
    except SyntaxError:
        value = None
    if value is None: 
        print "Blank value. Enter floating point number"

0

Source: https://habr.com/ru/post/1756408/


All Articles