问题是:-修改first_和_last函数,使其在字符串的第一个字母与最后一个字母相同时返回True,在不同时返回False。请记住,您可以使用消息[0]或消息[-1]访问字符。 注意如何处理空字符串,空字符串应该返回True,因为nothing等于nothing
当我这样写代码时:-
def first_and_last(message):
if len(message) == 0:
return True
elif message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# output:-
True
False
True
但当我这样写代码时:-
def first_and_last(message):
if message[0] == message[-1]:
return True
elif len(message) == 0:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# output:-
True
False
Traceback (most recent call last):
File "C:/Users/Sidje/PycharmProjects/untitled2/SId.py", line 11, in <module>
print(first_and_last(""))
File "C:/Users/Sidje/PycharmProjects/untitled2/SId.py", line 2, in first_and_last
if message[0] == message[-1]:
IndexError: string index out of range
当我用elif写len函数时,当语句为空时程序不工作,但在其他条件下它工作。 为什么呢
'发送“(空)值时,调用函数消息[0],消息[-1]无法在所述索引中找到值:
请注意,if函数先执行,然后执行其余的conidtions
在以下情况下(第二个代码块),“if”条件尝试访问没有字符的字符串的第一个字符。这会导致错误
在另一种情况下(第一个块),此错误永远不会发生,因为如果字符串没有字符,则永远不会达到该条件,因为满足第一个条件后将跳过“elif”
相关问题 更多 >
编程相关推荐