How to have user true/false input in python?

前端 未结 7 524
野的像风
野的像风 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: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")
    

提交回复
热议问题