User input boolean in python

Trying to convert your input to bool won’t 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 wasn’t "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").

Leave a Comment