How can I limit the user input to only integers in Python

前端 未结 4 741
盖世英雄少女心
盖世英雄少女心 2020-11-29 10:37

I\'m trying to make a multiple choice survey that allows the user to pick from options 1-x. How can I make it so that if the user enters any characters besides numbers, retu

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 11:14

    The best way would be to use a helper function which can accept a variable type along with the message to take input.

    def _input(message,in_type=str):
        while True:
          try:
            return in_type (input(message))
        except:pass
    
    if __name__ == '__main__':
        _input("Only accepting integer : ",int)
        _input("Only accepting float : ",float)
        _input("Accepting anything as string : ")
    

    So when you want an integer , you can pass it that i only want integer, just in case you can accept floating number you pass the float as a parameter. It will make your code really slim so if you have to take input 10 times , you don't want to write try catch blocks ten times.

提交回复
热议问题