This function returns True if the first letter of the string is the same as the last letter of the string and False if they’re different.
I'm having trouble explaining why I have the following error with this code:
I'm having trouble explaining why I have the following error with this code:
def first_and_last(message): if message[0] == message[-1]: return True return False print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last(""))
Error:Error on line 2:
if message[0] == message[-1]:
IndexError: string index out of range
But if I just add a logical operator it doesn't have an error, my question is why? if both are basically the same, I think the same error should pop out because I'm not doing anything special to specify any input for the second one.def first_and_last(message): if message == "" or message[0] == message[-1]: return True return False print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last(""))
Output:True
False
Thanks for reading.