【问题标题】:How do I get a boolean value from an input?如何从输入中获取布尔值?
【发布时间】:2019-12-30 23:41:18
【问题描述】:

我想问用户一个真/假问题并从中获取一个布尔值,但我真的不明白.bool() 是如何工作的。这更像是“我能做什么?”而不是“有什么问题?”。

例如,这就是我的代码的样子:

question = input("Is the Earth flat? ")
if question.bool() is True:
     print("You dumb.")

我知道这是不正确的,但我不确定什么会起作用!

是什么让.bool() 注册为真或假?

我认为这可能是我必须做的,但似乎不对:

if question == "Yes" or "Yeah" or "Y" or "Duh".lower()
     print("You dumb.")

【问题讨论】:

    标签: python boolean


    【解决方案1】:

    为此使用in,而不是多个or 语句,因为它的正确形式可读性较差且效率较低。 sets 也非常适合检查包容性。

    question = input("Is the Earth flat? ")
    if question.lower() in {"yes", "yeah", "y", "duh"}:
         print("You dumb.")
    

    您甚至可以创建一个自定义函数来提出问题并返回布尔结果

    def ask_bool(question):
        return input(question).lower() in {"yes", "yeah", "y", "duh"}
    

    然后要求一个布尔答案:

    if ask_bool("Is the Earth flat? "):
         print("You dumb.")
    

    【讨论】:

      【解决方案2】:

      使用element in list:

      if question.lower() in ["yes", "yeah", "y", "duh"]:
           print("You dumb.")
      

      【讨论】:

        【解决方案3】:

        对于您的第二个选项,这不起作用,因为 python 不了解其他条件是什么。检查多个条件是否相等的正确方法如下

        if (question == "Yes" or question == "Yeah" or question == "Y" or question == "Duh".lower())
             print("You dumb.")
        

        但是,这可能不是使用这么多术语的最佳方法,最好将它们存储在列表中并迭代。

        【讨论】:

          【解决方案4】:

          我建议使用列表中的元素:在 [] 之间,您只需列出您可以接受和处理的所有可能答案。

          if question.lower() in ["Yes", "YES", "true", "TRUE"]:
               print("You dumb!")
          else:
               print("You are not stupid!")
          

          希望这会有所帮助。

          【讨论】:

            【解决方案5】:

            我得到了一个默认是回答的解决方案

            ans = input("Your answer [Y/n]: ")
            
            if ans.lower() == "n":
                # nooooo 
            else:
                # yessss 
            

            不过你也应该看到这个,https://stackoverflow.com/a/48817835/10362396

            【讨论】:

              【解决方案6】:
              question = input("Is the Earth flat? ")
              
              if question.lower() == "Yes".lower() or question.lower() == "Yeah".lower():
                print(question)
                print("You dumb.")
              

              【讨论】:

                猜你喜欢
                • 2022-07-06
                • 2019-02-11
                • 1970-01-01
                • 2015-11-12
                • 1970-01-01
                • 2020-10-01
                • 2014-02-12
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多