11

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)
6
  • Hint: Test with an empty input. Commented Feb 15, 2018 at 22:39
  • Well: 1. any non-empty string input will evaluate truth-y; and 2. neither Boolean value is equal to either of the strings "True" or "False". Also the parentheses in that equality evaluation are redundant. You could just skip the bool; "True" == "True". Commented Feb 15, 2018 at 22:39
  • Why are you converting the user input to boolean, then comparing it to strings? Just don't convert it. Commented Feb 15, 2018 at 22:41
  • 2
    Remove the bool statement before input should work fine Commented Feb 15, 2018 at 22:43
  • 1
    Also if you want to return Boolean values why are you printing strings ('True'). Instead use Return True Commented Feb 15, 2018 at 22:48

14 Answers 14

14

Keep it simple:

isSure = input('Are you sure? (y/n): ').lower().startswith('y')
  • Result is always bool;
  • Capitals are ignored;
  • True only if it starts withy;
  • Everything else equals to False;
Sign up to request clarification or add additional context in comments.

Comments

12

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

9 Comments

Yes, but why would you use two if-statements and not elif?
Eh, mainly just trying to stay consistent with the OP's code @Anton.
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.
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.
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()).
|
4

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

Comments

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"

3 Comments

Why not push it even further and simply write return input("Do you like spicy food? True or False?") == "True"
@A.Smoliak Readability first. But yeah with programming there are lots of options.
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.
1

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)

1 Comment

how do i do that?
1

Try this. Ask for answer in 0 and 1 and then convert that to boolean value. Like I did in the example below

isTrue = True
while isTrue:
  isTrue = bool(int(input("Continue? 1 for yes, 0 for no: ")))

Comments

1

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

4 Comments

Use this to make them boolean and can be used later on as boolean
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.
It would be helpful if you edited your question to provide some context and explanation of how this code answers the question.
i'm a new contributor so thanks for the feedback i will definitely be looking into this
0

As Christian Dean pointed, bool(input()) will return True for any not-null input. If you really need to use a bool, you could force it this way:

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

    return(likes_spicyfood)

This is a workaround, "translating" the input string to a bool (spicyfood_Bool). No need to say that this solution is overcomplicated, but it will do de job if you really need a bool.

Comments

0

you can simply use this

inp=input('Do you like spicy food? True or False?')
spicyfood = True if inp== 'True' else  False if inp=='False'

Comments

0
spicyfood = bool(input("Do you like spicy food? t/f?")=='t')

1 Comment

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
0

You could also use module "ast" with "literal_eval"-Method. Like this:

import ast

bool = ast.literal_eval(input("True or False?"))

1 Comment

It will fail on inputs like: ast.literal_eval("false")
0

any non-empty string input will evaluate truth-y; and 2. neither Boolean value is equal to either of the strings "True" or "False". Also the parentheses in that equality evaluation are redundant. You could just skip the bool; "True" == "True". – jonrsharpe.

An alternate code is to set the question in a "while loop" and pass the choices in a list;

name = input("What is your name?")
while True:
    spicyfood = input("Do you like spicy food? yes or no?")
    if spicyfood not in ["yes","no"]:
        print("Please type yes or no")
        continue
    else:
        break
if spicyfood == ("yes"):
    print(name+" "+ "likes spicy food")
else:
    print(name+" "+ "hates spicy food")

Comments

0

here's mine (a newbie) with a bit similar problem and finally dicide not to make it as boolean

propworth = input("how much is your prop worth?")
finalcost=0.1*int(propworth)
finalcost2=0.2*int(propworth)
def funx():
    while True:
        creditevaluation= input("is the debt credit good or bad?")
        if creditevaluation.lower() =="good":
            print(f'10% downpayment is needed')
            print(f'as said 10% x {propworth}')
            print(f'downpayment: {finalcost}$')
        if creditevaluation.lower() =="bad":
            print (f'20% down payment is needed')
            print(f'as said 20% x {propworth}')
            print (f'downpayment: {int(finalcost2)}$')
        else :
            creditevaluation.lower() != "good","bad"
            print("Please type good or bad")
            return funx()
        break 
funx()
print ("""debt will be sent to your account !!!
thx for choosing our service""")```

come for some rep lol

Comments

0

A very simple solution

def likes_spicy_food():
    inp = input("Do you like spicy food? Yes or No")
    
    if inp == "Yes":
        return True
    else:
        return False

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including at least one that has been validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.