How to have user true/false input in python?

前端 未结 7 510
野的像风
野的像风 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:40
    def get_bool(prompt):
    while True:
        try:
            return {"si": True, "no": False}[input(prompt).lower()]
        except KeyError:
            print ("Invalido ingresa por favor si o no!")
    
        respuesta = get_bool("Quieres correr este programa: si o no")
    
    if (respuesta == True):
        x = 0
    else:
        x = 2
    
    0 讨论(0)
  • 2021-01-19 11:41
    johnnyHungry = input("Is johnny hungry ")
    if johnnyHungry == "True":
    ...
    

    I expect that you can take it from there?

    0 讨论(0)
  • 2021-01-19 11:42

    I hope this code works for you. Because I already tried this code and it worked fine.

    johnnyHungry = str(input("Is johnny hungry ")) 
    
    def checking(x):
        return 'yes' == True
        return 'no' == False
    
    if checking(johnnyHungry) == True:
        print("Johnny needs to eat.")
    elif checking(johnnyHungry) == False:
        print("Johnny is full.")
    

    I'm sorry if it's long, I'm new to programming either.

    0 讨论(0)
  • 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!"
    
    0 讨论(0)
  • 2021-01-19 11:55

    You can turn something into True or False using bool:

    >>> bool(0)
    False
    >>> bool("True")
    True
    >>> bool("")
    False
    

    But there is a problem with a user entering "True" or "False" and assuming we can turn that string into a bool:

    >>> bool("False")
    True
    

    This is because a string is considered truthy if it's not empty.

    Typically, what we do instead is allow a user to enter a certain subset of possible inputs and then we tell the user that only these values are allowed if the user enters something else:

    user_answer = input("Is johnny hungry ").lower().strip()
    if user_answer == "true":
        # do something
    elif user_answer == "false":
        # do something else
    else:
        print("Error: Answer must be True or False")
    
    0 讨论(0)
  • 2021-01-19 11:57

    You could just try bool(input("...")) but you would get into trouble if the user doesn't input a bool. You could just wrap it in a try statement.

    0 讨论(0)
提交回复
热议问题