first_and_last 関数は、メッセージ [0] またはメッセージ [-1] を使用して文字にアクセスし、文字列の最初の文字が文字列の最後の文字と同じ場合は True、異なる場合は False を返します。空の文字列の条件をチェックしているときに、次のエラーが発生します。
Error on line 2:
if message[0] == message[1] :
IndexError: string index out of range
なぜこのエラーが発生するのかわかりません。以下は私のコードです:
def first_and_last(message):
if message[0] == message[-1] or len(message) == 0:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))