python中的用户输入布尔值 [英] User input boolean in python
问题描述
我试图让用户输入他们是否喜欢辛辣食物,并且输出应该是布尔值,但是我的以下代码似乎没有输出:
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)
推荐答案
尝试将您的输入转换为bool
不会那样. Python认为任何非空字符串True
.因此,执行bool(input())
基本上与执行input() != ''
相同.即使输入不是"True"
,两者都返回true.只需将直接给定的输入与字符串"True
和"False"
进行比较:
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
请注意,如果输入不是"True
或"False"
,则上述代码将失败(通过返回None
而不是布尔值).考虑返回默认值或重新询问用户输入,如果原始输入无效(即不是"True
或"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"
).
这篇关于python中的用户输入布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!