python中布尔值是false_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)

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值