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)
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"
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With