I am learning how to use python, and yesterday I got a question which is described like this:
Modify the first_and_last function so that it returns True if the first letter of the string is the same as the last letter of the string, False if they’re different.
By trying to solve this, I found that there are 2 almost same program, but one can run correctly, the other calls an error: string index out of range
Program 1 (This can run correctly)
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(""))
Program 2(This calls an error)
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(""))
I just want to know what's the difference between these 2 programs, and why they return the different results. Appreciate it for your help!
message[0]
, i.e. the first letter of the string, gives an an exception that the index is out of bounds. There is no such character in the string. You first code is correct: check to make sure the character exits before looking at its value. Your code could be simplified to justreturn len(message) == 0 or message[0] == message[-1]
. You don't need theif
statement. – Frank Yellin Oct 25 '20 at 2:05