python library for user input

前端 未结 5 1668
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 17:37

I am implementing a small command line tool in python that needs to ask the user a couple of questions. I use

raw_input(\'Are you male or female?\')
<         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-05 18:21

    I don't know if such a library exists, but you could write an high-order function like this:

    def check_input(predicate, msg, error_string="Illegal Input"):
        while True:
            result = input(msg).strip()
            if predicate(result):
                return result
            print(error_string)
    
    result = check_input(lambda x: x in ['male', 'female'],
                                       'Are you male or female? ')
    print(result)
    

    Output:

    Are you male or female? foo
    Illegal Input
    Are you male or female? bar
    Illegal Input
    Are you male or female? Male
    Illegal Input
    Are you male or female? male
    male
    

提交回复
热议问题