首页 > 解决方案 > if not 声明解释

问题描述

此代码是在我找到的答案中提供的,但没有解释。我想知道为什么需要包含“非消息”才能使其正常工作?

def first_and_last(message):
    if not message or message[0] == message[-1]:
        return True
    else:
        return False

标签: pythonif-statement

解决方案


If message happens to be an empty list [] then you will throw an IndexError because message[0] and message[-1] do not exist in the list.

Generally, if not checks to see if something is Truthy or Falsey. (A great example of what is falsey is here)

In this example, if you pass [] which happens to be falsey, it will trigger the boolean comparison and since comparisons like or are lazy loaded, it will not even check message[0] == message[-1] which would throw an error.

If you know that message always be a list and will never be Falsey (i.e. None, [], '', etc.) then you do not need it.


推荐阅读