User input boolean in python

61,262

Solution 1

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").

Solution 2

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 you'll 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 you'll have to change is that you'll 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()

You'll also see that I've returned some redundant parenthesis: when comparing the input value to 'True' or 'False' and when returing likes_spicyfood. Here's more on converting a string to a bool

Solution 3

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"

Solution 4

Don't cast the input as a bool. Later make a condition that checks whether it is True or False

Something like this :)

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

Solution 5

First we'll need to read the user's input after they read the question:

hungry = input("Are you hungry? True or False \n")

Now that we have their response in a variable, hungry, we're able to use it in some statements:

if hungry.lower() == "true":

Notice the use of .lower(), which will take their string, regardless of capitalisation of letters, and convert it all to lowercase. This means that whether they enter "True", "tRue" or "TRUE", they will all evaluate to being True if compared to the lowercase counterpart "true".

What's important when doing this, is to always have your comparison string be lowercase as well. because if you tried evaluating "true" against "True", it would return False.

Using this knowledge, we're able to put it all together and print out what we want:

hungry = input("Are you hungry? True or false \n")

if hungry.lower() == "true":
    print("Feed me!")
else:
    print("I'm not hungry.")
Share:
61,262
user5556453
Author by

user5556453

Updated on July 09, 2022

Comments

  • user5556453
    user5556453 almost 2 years

    I am trying to have a user input whether or not they like spicy food and the output is supposed to be a boolean but I don't seem to be getting an output with my code below:

    def likes_spicyfood():
        spicyfood = bool(input("Do you like spicy food? True or False?"))
        if spicyfood == ("True"):
            print("True")
        if spicyfood == ("False"):
            print("False")
            return(likes_spicyfood)
    
  • Anton vBR
    Anton vBR about 6 years
    Yes, but why would you use two if-statements and not elif?
  • Christian Dean
    Christian Dean about 6 years
    Eh, mainly just trying to stay consistent with the OP's code @Anton.
  • A. Smoliak
    A. Smoliak about 6 years
    to be honest it's pretty confusing on why the OP has decided to write such a strange program, I would guess that they are merely practicing.
  • Christian Dean
    Christian Dean about 6 years
    Yep, probably so @A.Smoliak. I wasn't exactly sure why he wanted to try to return his function object, so that's one thing I to the liberty of removing. Nice answer by the way! I was sure to upvote it :-)
  • A. Smoliak
    A. Smoliak about 6 years
    Why not push it even further and simply write return input("Do you like spicy food? True or False?") == "True"
  • Anton vBR
    Anton vBR about 6 years
    @A.Smoliak Readability first. But yeah with programming there are lots of options.
  • Christian Dean
    Christian Dean about 6 years
    Yep @A.Smoliak, Anton's right. From the Python zen: "Readability counts." ;-) Of course, it's not a hard-set rule. There are certain cases where you have to put performance over readability, but those are pretty rare in Python.
  • user5556453
    user5556453 about 6 years
    This is my first time taking python and i'm doing a homework assignment and I don't get if functions at all so that's why I came up with a confusing program, I'm sorry. We just learnt return and if so that is why they require us to return at the end of every function
  • Christian Dean
    Christian Dean about 6 years
    No worries @user5556453. We all have to start somewhere :-) Before making posting your next post however, I recommend you take the tour and visit the help-center to become familiar with how Stack Overflow works.
  • user5556453
    user5556453 about 6 years
    Does this function print out the users answer?
  • Christian Dean
    Christian Dean about 6 years
    No, it doesn't @user5556453. The function is named likes_spicyfood so I assumed it should return a boolean representing whether the user likes spicy food. If you want to print the user's answer, just do print(likes_spicyfood()).
  • user5556453
    user5556453 about 6 years
    how do i do that?
  • user5556453
    user5556453 about 6 years
    Oh, its supposed to return a boolean value!
  • Yunnosch
    Yunnosch about 4 years
    This is considered a code-only answer. Please add an explanation in order to help fighting the misconception that StackOverflow is a free programming service. Also, for future contribution, please take the tour and have a look at stackoverflow.com/editing-help
  • Ancient_Sinner
    Ancient_Sinner almost 4 years
    Use this to make them boolean and can be used later on as boolean
  • Jaimil Patel
    Jaimil Patel almost 4 years
    Hope It will solve issue but please add explanation of your code with it so user will get perfect understanding which he/she really wants.
  • Dragonthoughts
    Dragonthoughts almost 4 years
    It would be helpful if you edited your question to provide some context and explanation of how this code answers the question.
  • Ancient_Sinner
    Ancient_Sinner almost 4 years
    i'm a new contributor so thanks for the feedback i will definitely be looking into this
  • taras
    taras about 3 years
    It will fail on inputs like: ast.literal_eval("false")