如何确定输入何时是字母?

时间:2010-10-19 09:19:57

标签: python validation user-input

我一直试图解决这个问题,似乎无法让它正常工作..这是我目前的工作

while True:

    guess = int(raw_input('What is your number?'))

    if 100 < guess or guess < 1:
        print '\ninvalid'

    else:
        .....continue on

现在我已经这样做了当用户输入一个高于100或低于1的数字时,它打印出“无效”。但是,如果我想在用户输入不是数字的字符串(字母,标点符号等)时这样做,那么它也会返回这个“无效”的消息吗?

我已经考虑过使用if not ... isdigit(),但它不会起作用,因为我将猜测作为一个整数来使上述范围起作用。 Try / except是我想到的另一种选择,但仍然没有弄清楚如何正确实现它。

2 个答案:

答案 0 :(得分:6)

您可以使用异常处理:

try:
    guess = int(raw_input('What is your number?'))
    if not (1 <= guess <= 100):
        raise ValueError
    # .....continue on
except ValueError:
    print '\ninvalid'

这样,如果用户输入非数字字符串或输入大于100或小于1的数字字符串,将打印\ninvalid

编辑:好的,我提交了x < y < z语法。但是,当它与not一起使用时,仍然认为它失去了一些魅力。

答案 1 :(得分:5)

while True:
  try:
    guess = int(raw_input("..."))
  except EOFError:
    print "whoa nelly! EOF? we should probably exit"
    break  # or sys.exit, or raise a different exception,
    # or don't catch this at all, and let it percolate up,
    # depending on what you want
  except ValueError:
    print "illegal input: expected an integer"
  else:
    if not (1 <= guess <= 100):
      print "out of range"
    else:
      print "processing guess... (but if it wasn't 42, then it's wrong)"
      break  # out of while loop after processing