为什么此定义返回False而不是True?

时间:2019-09-06 05:16:07

标签: python-3.7

我不明白为什么它只检查列表的第一个数字。 (has23([4,3])中的数字4会中断。为什么不返回并检查数字3?我需要这个定义来返回True。

我一直试图用一个'elif'分隔它,但是没有运气。

def has23(nums):
  for num in nums:
    if num == 2 or num == 3:
      return True

    else:
      return False

has23([4, 3])

无错误信息。它返回false而不是True。

3 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为只要满足<c:forEach items="${files}" var="file"> <tr> <td>${file.name}</td> <td>${file.createdOn}</td> <td><a href="http://localhost:8080/dms/getFile?filePath=${file.realPath}" target="search_iframe">Open PDF</a></td> </tr> </c:forEach> </table> <iframe src="" width="100%" height="100%" name="search_iframe"></iframe> </body> if的条件else就将其从return中删除。因此,最好将结果存储在列表中,并def存储在列表中。 return

答案 1 :(得分:0)

问题是return语句,如果数组中的第一个值不符合条件,它将中断for循环并返回false。

代码应该是这样的(我不是python编码器)

def has23(nums):
  for num in nums:
    if num == 2 or num == 3:
      return True
  return False  # This return statement should be after the for loop
has23([4, 3])

答案 2 :(得分:0)

def has23(nums):
    if 2 in nums or 2 in nums:
        return True
    else:
        return False

has23([4, 2])

希望这会起作用