How to have user true/false input in python?

前端 未结 7 592
野的像风
野的像风 2021-01-19 11:00

I\'m new to python.

I want the program to ask

\"is Johnny hungry? True or false?\"

user inputs True then print is

7条回答
  •  情深已故
    2021-01-19 11:44

    you can use a simple helper that will force whatever input you want

    def get_bool(prompt):
        while True:
            try:
               return {"true":True,"false":False}[input(prompt).lower()]
            except KeyError:
               print "Invalid input please enter True or False!"
    
    print get_bool("Is Jonny Hungry?")
    

    you can apply this to anything

    def get_int(prompt):
        while True:
            try:
               return int(input(prompt))
            except ValueError:
               print "Thats not an integer silly!"
    

提交回复
热议问题