开发者

Checking for empty number as input

开发者 https://www.devze.com 2023-01-08 14:06 出处:网络
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)

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 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

0

精彩评论

暂无评论...
验证码 换一张
取 消