Hello I'm learning to code Python and I ran into this issue where the order of the code affected its ability to run. The first code works while the second doesn't. I'd appreciate a relatively simple explanation as I'm still a novice, thanks!
Prompt:
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. Remember that you can access characters using message[0] or message[-1]. Be careful how you handle the empty string, which should return True since nothing is equal to nothing.
Code 1 (works):
def first_and_last(message):
if len(message)==0:
return True
if message[0]==message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
Code 2 (does not work):
def first_and_last(message):
if message[0]==message[-1]:
return True
if len(message)==0:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
Error message "IndexError: string index out of range"
CodePudding user response:
When accessing the character of the string using message[0] and message[-1], you are making the assumption that message is not empty.
Therefore, when you try to access something that doesn't exist (which happens when you set message=""), it will return the error.
The first code works because it checks for possible "extreme" case, and immediately returns if this condition is met, otherwise it tries the other cases (which will not launch the IndexError since that case is already dealt with the first if)
This is due to the fact that all the code is executed sequentially, and therefore the order of different if cases matters.
CodePudding user response:
Because message[0]
and message[-1]
doesn't exist when you try to call the function with ""
CodePudding user response:
In this case
def first_and_last(message):
if len(message)==0:
return True
if message[0]==message[-1]:
return True
else:
return False
When message length is zero, you return True
, one of return
effects is
leaves the current function call
so code after it will be not reached.