User input boolean in python

User input boolean in python

Trying to convert your input to bool wont work like that. Python considers any non-empty string True. So doing bool(input()) is basically the same as doing input() != . Both return true even if the input wasnt True. Just compare the input given directly to the strings True and False:

def likes_spicyfood():
    spicyfood = input(Do you like spicy food? True or False?)
    if spicyfood == True:
        return True
    if spicyfood == False:
        return False

Note that the above code will fail (by returning None instead of a boolean value) if the input is anything but True or False. Consider returning a default value or re-asking the user for input if the original input is invalid (i.e not True or False).

In your usage, converting a string to a bool will not be a solution that will work. In Python, if you convert a string to a bool, for example: bool(False) the boolean value will be True, this is because if you convert a non-empty string to a bool it will always convert to True, but if you try to convert an empty string to a bool youll get False.

To solve your issue several changes have to be made.
First off your code sample does not even call the function where you ask the user whether they like spicy food or not, so call it on the very bottom of the code.
likes_spicyfood()

Second thing youll have to change is that youll have to simply have the user type True or False like you have in your code, but instead of converting the value from string to bool, simply take the string and compare it to either True or False, here is the full code:

def likes_spicyfood():
    spicyfood = input(Do you like spicy food? True or False?)
    if spicyfood == True:
        print(The user likes spicy food!)
    if spicyfood == False:
        print(The user hates spicy food!)
    return likes_spicyfood

likes_spicyfood()

Youll also see that Ive returned some redundant parenthesis: when comparing the input value to True or False and when returing likes_spicyfood.
Heres more on converting a string to a bool

User input boolean in python

If you are certain input is correct you can do:

def likes_spicyfood():
    spicyfood = input(Do you like spicy food? True or False?)
    return spicyfood.title() == True

Leave a Reply

Your email address will not be published.