如何将用户输入限制为 Python 中的整数

新手上路,请多包涵

我正在尝试进行多项选择调查,允许用户从选项 1-x 中进行选择。我怎样才能做到这一点,如果用户输入数字以外的任何字符,则返回类似“这是无效答案”的内容

def Survey():
    print('1) Blue')
    print('2) Red')
    print('3) Yellow')
    question = int(input('Out of these options\(1,2,3), which is your favourite?'))
    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

原文由 user3578683 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 686
2 个回答

您的代码将变为:

 def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

它的工作方式是创建一个无限循环,直到只输入数字。所以说我输入“1”,它会打破循环。但如果我放“Fooey!”本应引发的错误被 except 语句捕获,并且它循环,因为它没有被破坏。

原文由 HarryCBurn 发布,翻译遵循 CC BY-SA 3.0 许可协议

最好的方法是使用一个辅助函数,它可以接受一个变量类型以及接受输入的消息。

 def _input(message, input_type=str):
    while True:
      try:
        return input_type (input(message))
    except:pass

if __name__ == '__main__':
    _input("Only accepting integer : ", int)
    _input("Only accepting float : ", float)
    _input("Accepting anything as string : ")

所以当你想要一个整数时,你可以传递它我只想要整数,以防万一你可以接受浮点数你将浮点数作为参数传递。它会让你的代码非常精简,所以如果你必须输入 10 次,你不想写 try catch 块十次。

原文由 Ahsan Roy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题