9

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)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user5556453
  • 157
  • 1
  • 1
  • 8
  • Hint: Test with an empty input. – heemayl Feb 15 '18 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"`. – jonrsharpe Feb 15 '18 at 22:39
  • Why are you converting the user input to boolean, then comparing it to strings? Just don't convert it. – Christian Dean Feb 15 '18 at 22:41
  • 2
    Remove the bool statement before input should work fine – mgracer Feb 15 '18 at 22:43
  • 1
    Also if you want to return Boolean values why are you printing strings ('True'). Instead use Return True – Moller Rodrigues Feb 15 '18 at 22:48
  • This returning a function. It seems much more likely that you want to return spicyfood (the boolean variable), rather than likes_spicyfood (the function itself). Also, the return should be outside of the second if statement, otherwise it won't always return a value. – Brian Minton Jun 03 '20 at 17:34

13 Answers13

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

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • Yes, but why would you use two if-statements and not `elif`? – Anton vBR Feb 15 '18 at 22:58
  • 1
    Eh, mainly just trying to stay consistent with the OP's code @Anton. – Christian Dean Feb 15 '18 at 22:59
  • 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. – A. Smoliak Feb 15 '18 at 23:00
  • 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 :-) – Christian Dean Feb 15 '18 at 23:01
  • 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 – user5556453 Feb 15 '18 at 23:23
  • 1
    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](https://stackoverflow.com/help) to become familiar with how Stack Overflow works. – Christian Dean Feb 15 '18 at 23:24
  • Does this function print out the users answer? – user5556453 Feb 15 '18 at 23:26
  • 1
    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())`. – Christian Dean Feb 15 '18 at 23:31
  • Oh, its supposed to return a boolean value! – user5556453 Feb 15 '18 at 23:51
8

Keep it simple:

isSure = input('Are you sure? (y/n): ').lower().strip() == 'y'
  • Result is always bool;
  • Capitals are ignored;
  • True only if it contains y and maybe some spaces;
  • Everything else equals to False;
Wellington
  • 151
  • 1
  • 3
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

A. Smoliak
  • 438
  • 2
  • 17
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"
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • 1
    Why not push it even further and simply write `return input("Do you like spicy food? True or False?") == "True"` – A. Smoliak Feb 15 '18 at 23:03
  • 3
    @A.Smoliak Readability first. But yeah with programming there are lots of options. – Anton vBR Feb 15 '18 at 23:04
  • Yep @A.Smoliak, Anton's right. [From the Python zen](https://www.python.org/dev/peps/pep-0020/#id3): _"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. – Christian Dean Feb 15 '18 at 23:06
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)
Aura
  • 35
  • 7
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: ")))
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.")
Diggy.
  • 6,744
  • 3
  • 19
  • 38
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.

Pepv
  • 76
  • 15
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'
0
spicyfood = bool(input("Do you like spicy food? t/f?")=='t')
Das_Geek
  • 2,775
  • 7
  • 20
  • 26
KemTom
  • 1
  • 5
    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 https://stackoverflow.com/editing-help – Yunnosch Feb 03 '20 at 21:30
0

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

import ast

bool = ast.literal_eval(input("True or False?"))
andiw
  • 1
  • 1
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")
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