如何确保用户输入数字或循环将继续

时间:2015-10-01 00:54:31

标签: python python-2.7 loops

我无法验证用户输入。我需要代码来继续询问什么是抵消'除非输入数字。如果输入字母空格特殊字符,则应该再次询问问题。

while True:
    offset=int(raw_input('what is offset (decimals will be ignored)'))
    if offset >=0 and offset<=26:
        break

2 个答案:

答案 0 :(得分:3)

while True:
    try:
      offset=int(raw_input('what is offset (decimals will be ignored)'))
      if offset >=0 and offset<=26:
        break
    except ValueError:
      pass

(换句话说,如果raw_input抛出异常,只要它的ValueError(因此用户可能仍然按下control-c退出应用程序)就跳过它

答案 1 :(得分:1)

也许像这段代码?

'''
question.py
'''

#define function

def question():

    import sys

    #try to get get a number
    try:
        #get input from user
        offset = int(raw_input('what is offset? (decimals will be ignored) '))
        if offset >=0 and offset <=26:
            print offset
        else:question()
    #all other exceptions
    except:
        question()
        #sys.exit(1)#abort

#run program
question = question()