samedi 24 octobre 2020

Issues about if-statement and empty string in Python

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!

Aucun commentaire:

Enregistrer un commentaire