def first_and_last(message):
if not message or message[0] == message[-1]:
return True
else:
return False
The function you wrote returns True, if message is 'empty' or first ([0]
) and last ([-1]
) character (or item, it could be list/tuple as well) of the message
are the same; otherwise returns False.
Specifically if not message
piece you are asking about checks whether parameter message
is not 0
, ""
, None
and so on. That keeps you safe from IndexError: string index out of range
too, so that you wouldn't call an item when there is no list/tuple at all.
Analyze the following:
def test(message):
if not message:
print("Foo")
else:
print("Bar")
if __name__ == "__main__":
message = ""
test(message)
When you run this code, "Foo" will be printed. Type in some characters between the quotation marks in message
and "Bar" will appear.