如何在python中输入用户真/假?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32616548/
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 11:55:50  来源:igfitidea点击:

How to have user true/false input in python?

python

提问by Matt

I'm new to python.

我是python的新手。

I want the program to ask

我要程序问

"is Johnny hungry? True or false?"

user inputs Truethen print is "Johnny needs to eat."

用户输入 True然后打印是"Johnny needs to eat."

user inputs falsethen print "Johnny is full."

用户输入 false然后打印"Johnny is full."

I know to add an int I type in

我知道要添加一个我输入的 int

johnnyHungry = int(input("Is johnny hungry ")) 

but I want them to enter True/false, not an int.

但我希望他们输入 True/false,而不是 int。

回答by erewok

You can turn something intoTrueor Falseusing bool:

您可以将某些内容转换为TrueFalse使用bool

>>> bool(0)
False
>>> bool("True")
True
>>> bool("")
False

But there is a problem with a user entering "True" or "False" and assuming we can turn that stringinto a bool:

但是用户输入“True”或“False”并假设我们可以将其string转换为布尔值时存在问题:

>>> bool("False")
True

This is because a stringis considered truthyif it's not empty.

这是因为string被认为是truthy如果它不是空的。

Typically, what we do instead is allow a user to enter a certain subset of possible inputs and then we tell the user that onlythese values are allowed if the user enters something else:

通常,我们做的是允许用户输入可能输入的某个子集,然后我们告诉用户如果用户输入其他内容,则只允许这些值:

user_answer = input("Is johnny hungry ").lower().strip()
if user_answer == "true":
    # do something
elif user_answer == "false":
    # do something else
else:
    print("Error: Answer must be True or False")

回答by Prune

johnnyHungry = input("Is johnny hungry ")
if johnnyHungry == "True":
...

I expect that you can take it from there?

我希望你能从那里拿走它?

回答by newDelete

You could just try bool(input("...")) but you would get into trouble if the user doesn't input a bool. You could just wrap it in a try statement.

您可以尝试 bool(input("...")) 但如果用户不输入 bool 就会遇到麻烦。您可以将其包装在 try 语句中。

回答by Joran Beasley

you can use a simple helper that will force whatever input you want

你可以使用一个简单的助手来强制你想要的任何输入

def get_bool(prompt):
    while True:
        try:
           return {"true":True,"false":False}[input(prompt).lower()]
        except KeyError:
           print "Invalid input please enter True or False!"

print get_bool("Is Jonny Hungry?")

you can apply this to anything

你可以把它应用到任何东西上

def get_int(prompt):
    while True:
        try:
           return int(input(prompt))
        except ValueError:
           print "Thats not an integer silly!"

回答by ljlizarraga

def get_bool(prompt):
while True:
    try:
        return {"si": True, "no": False}[input(prompt).lower()]
    except KeyError:
        print ("Invalido ingresa por favor si o no!")

    respuesta = get_bool("Quieres correr este programa: si o no")

if (respuesta == True):
    x = 0
else:
    x = 2

回答by MS_092420

I hope this code works for you. Because I already tried this code and it worked fine.

我希望这段代码对你有用。因为我已经尝试过这段代码并且效果很好。

johnnyHungry = str(input("Is johnny hungry ")) 

def checking(x):
    return 'yes' == True
    return 'no' == False

if checking(johnnyHungry) == True:
    print("Johnny needs to eat.")
elif checking(johnnyHungry) == False:
    print("Johnny is full.")

I'm sorry if it's long, I'm new to programming either.

如果它很长,我很抱歉,我也是编程新手。

回答by Lord Amazing

Code:

代码:

question = str(input("Is Johnny hungry?  Response: "))

if question == "yes":

    print("Johnny needs to eat food!")

if question == "no":

    print("Johnny is full!")

Run:

跑:

  1. Is Johnny hungry? Response: yes

    Johnny needs to eat food!

  2. Is Johnny hungry? Response: no

    Johnny is full!

  3. This is if you type something other than yes and no

    Is Johnny hungry? Response: lkjdahkjehlhd

  1. 强尼饿了吗?回应:是的

    约翰尼需要吃东西!

  2. 强尼饿了吗?回应:没有

    强尼吃饱了!

  3. 这是如果您输入的是和否以外的内容

    强尼饿了吗?回复:lkjdahkjehlhd

Nothing pops up/ there is no response

什么都没有弹出/没有响应