【问题标题】:Boolean check not working in function布尔检查在功能中不起作用
【发布时间】:2012-07-22 16:40:15
【问题描述】:

此代码将成为检查数字是否为质数的程序的一部分。我知道它不是特别优雅,但我想让它只是为了体验而工作。我认为函数失败是因为 if/elif 上的逻辑错误,当我运行这段代码时,它似乎直接进入 else 子句。这是语法问题,还是我不允许在 if 子句中进行逻辑检查?

list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

def find_prime(list, n):
    if n in list == False:
        list.append(n)
        print "I'ts in there now."
    elif n in list == True:
        print "It's in there already."
    else:
        print "Error"

find_prime(list, 3)
find_prime(list, 51)

【问题讨论】:

  • 你不应该命名一个变量listPython已经在使用那个标识符了。
  • 我不会对所有答案发表评论,我只想在这里说声谢谢,因为它们都有效:)
  • 至少接受一个答案....
  • 这解释了您当前的问题:stackoverflow.com/questions/9284350/…

标签: python list python-2.7


【解决方案1】:
  1. list 是变量的错误名称。它掩盖了内置的list

  2. if n in list == True: 不会执行您等待的操作:1 in [0, 1] == True 返回False(因为,正如@Duncan 所指出的,1 in [0,1] == True1 in [0,1] and [0,1] == True 的简写)。使用if n in li:if n not in li:

  3. Error 没有理由,因为元素在列表中或不在列表中。其他都是编程错误。

所以您的代码可能如下所示:

li = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

def find_prime(li, n):
    if n in li:
        print "It's in there already."
    else:
        li.append(n)
        print "It's in there now."

【讨论】:

  • 您答案的第 2 部分略有错误。如果它试图测试1 in False,你会得到一个异常。实际发生的是1 in [0,1] == True1 in [0,1] and [0,1] == True 的简写,and 之后的部分是 False。
  • @Duncan - 感谢您指出这一点。我已经更新了答案。
【解决方案2】:

不要打电话给你的名单list。称它为mylist 或其他名称。

使用if not n in mylistif n in mylist

【讨论】:

    【解决方案3】:

    由于该值要么在列表中,要么不在列表中,我认为您不需要检查 if/else 逻辑中的三个选项。

    list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
    
    def find_prime(list, n):
       if n in list:
          print "It's in there already."
       else:
          list.append(n)
          print "It's in there now."
    
    find_prime(list,3)
    find_prime(list,53)
    

    【讨论】:

      【解决方案4】:

      试试这个代码,而不是测试真/假。另请参阅我上面关于使用 list 作为变量名的评论(这是个坏主意,因为 Python 使用了该标识符)。

      mylist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
      
      def find_prime(mylist, n):
          if not n in mylist:
              mylist.append(n)
              print "I'ts in there now."
          else: # n in mylist:  has to be the case
              print "It's in there already."
      

      你不需要原来的最后一个else,你的选择是二进制的,要么在列表中,要么不在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多