我正在学习如何使用python,昨天我得到了一个问题,描述如下:
修改first_and_last函数,如果字符串的第一个字母与最后一个字母相同则返回True,如果不同则返回False。
通过尝试解决这个问题,我发现有2个几乎相同的程序,但一个可以正确运行,另一个调用错误:字符串索引超出范围
程序1(可以正确运行)
def first_and_last(message):
if len(message) == 0 or message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
程序 2(这会引发错误)
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(""))
我只想知道这两个程序有什么区别,以及为什么它们返回不同的结果。感谢您的帮助!
holdtom
Cats萌萌
慕标琳琳
慕桂英546537
精慕HU
相关分类