python中的用户输入布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48817461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:51:59  来源:igfitidea点击:

User input boolean in python

pythonpython-3.xinputboolean

提问by user5556453

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)

回答by Christian Dean

Trying to convert your input to boolwon'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 "Trueand "False":

尝试将您的输入转换为bool不会像那样工作。Python 考虑任何非空字符串True。所以doing和doingbool(input())基本一样input() != ''。即使输入不是,两者都返回 true "True"。只需将直接给定的输入与字符串进行比较,"True然后"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 Noneinstead of a boolean value) if the input is anything but "Trueor "False". Consider returning a default value or re-asking the user for inputif the original input is invalid (i.e not "Trueor "False").

请注意,None如果输入不是"Trueor ,则上述代码将失败(通过返回而不是布尔值)"False"。如果原始输入无效(即不是或),请考虑返回默认值或重新要求用户输入"True"False"

回答by A. Smoliak

In your usage, converting a stringto a boolwill 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.

在您的使用中,将 a 转换string为 abool将不是一个可行的解决方案。在 Python 中,如果您将字符串转换为 bool,例如:bool("False")布尔值将为True,这是因为如果您将非空字符串转换为 bool,它将始终转换为True,但如果您尝试将其转换为空字符串你会得到一个布尔值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()

要解决您的问题,必须进行多项更改。首先,你的代码示例甚至没有调用你询问用户是否喜欢辛辣食物的函数,所以在代码的最底部调用它。 likes_spicyfood()

Second thing you'll have to change is that you'll have to simply have the user type Trueor Falselike you have in your code, but instead of converting the value from stringto bool, simply take the stringand compare it to either 'True'or 'False', here is the full code:

您必须更改的第二件事是,您必须简单地拥有用户类型TrueFalse您在代码中拥有的类型,但不是将值从stringto转换bool,只需将 取值string并将其与'True'or进行比较'False',这里是完整代码:

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

您还将看到我返回了一些多余的括号:在将输入值与'True'or进行比较'False'时以及在返回时likes_spicyfood。这里有更多关于将字符串转换为 bool 的内容

回答by Anton vBR

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"

回答by Aura

Don't cast the input as a bool. Later make a condition that checks whether it is Trueor False

不要将输入转换为布尔值。稍后创建一个条件来检查它是True还是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)

回答by Aura

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

尝试这个。在 0 和 1 中询问答案,然后将其转换为布尔值。就像我在下面的例子中所做的那样

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

回答by Pepv

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:

正如 Christian Dean 所指出的,对于任何非空输入, bool(input()) 都将返回 True 。如果你真的需要使用 bool,你可以这样强制:

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.

这是一种变通方法,将输入字符串“翻译”为布尔值 (spicyfood_Bool)。无需说这个解决方案过于复杂,但如果你真的需要一个布尔值,它会起作用。

回答by Rajesh Sivasankaran

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'

回答by KemTom

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