【问题标题】:How to have user true/false input in python?如何在python中让用户输入真/假?
【发布时间】:2015-09-16 18:55:22
【问题描述】:

我是 python 新手。

我想让程序问

"is Johnny hungry? True or false?"

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

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

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

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

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

【问题讨论】:

  • ...如果用户输入的不是“真”或“假”怎么办?
  • 为什么一个大写而一个不大写?
  • 这不是很全面,但是有一个方便的库可以将真假字符串读取为布尔值:stackoverflow.com/questions/715417/… - 也可以使用 yaml 解析器,不确定我是否会推荐自己.

标签: python


【解决方案1】:

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

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

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

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

【讨论】:

  • 但是它可以返回除 T/F 以外的其他内容......我认为 OP 希望强制返回(但我也想过类似的事情:P 还是一样的好建议)跨度>
【解决方案2】:

您可以使用bool 将某些东西转换为 TrueFalse

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

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

>>> bool("False")
True

这是因为如果string 不为空,则将其视为真实

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

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

【讨论】:

  • 谢谢。我认为你的也不错,但对于一个全新的 Pythoner 来说可能有点困难。
  • 虽然if answer == "true":...elif answer == "false":... else:print "ERROR"可能会更好
【解决方案3】:
johnnyHungry = input("Is johnny hungry ")
if johnnyHungry == "True":
...

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

【讨论】:

  • 对于 python 初学者来说是一个很好的答案,即使它不是超级强大:P +1
【解决方案4】:
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

【讨论】:

    【解决方案5】:

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

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

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

    【讨论】:

    • 其实newDelete的回答没有错,和我的差不多。
    【解决方案6】:

    代码:

    question = str(input("Is Johnny hungry?  Response: "))
    
    if question == "yes":
    
        print("Johnny needs to eat food!")
    
    if question == "no":
    
        print("Johnny is full!")
    

    运行:

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

      约翰尼需要吃东西!

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

      约翰尼吃饱了!

    3. 这是如果您输入的不是“是”和“否”

      约翰尼饿了吗?回复:lkjdahkjehlhd

    没有弹出/没有响应

    【讨论】:

      【解决方案7】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        • 2018-12-25
        相关资源
        最近更新 更多