Himanshu kumar
Himanshu kumar

Reputation: 1

I want to check whether first and last letters of the words are same to return True else false. But it returns true every time

def first_last(message):
    for char in message:
        if char[0] == char[-1]:
            return True
        elif message == "":
            return True
        else:
            return False

I'm using it like this:

print(first_last("night")) # should return False
print(first_last("nun")) # should return True
print(first_last(""))   # should return true

Upvotes: 0

Views: 242

Answers (2)

fitz
fitz

Reputation: 580

When you use for loop you get a single character from message, then your comparison is meaningless.

You can try this:

def start_and_end_are_same(message):
    if message[:1] == message[-1:]:
        return True
    else:
        return False


print(start_and_end_are_same('night'))
print(start_and_end_are_same('nun'))
print(start_and_end_are_same(''))

Upvotes: 1

uranium235
uranium235

Reputation: 141

you don't need to loop through all characters.

def first_last(message): 
    if message == "": 
        return True 
    elif message[0] == message[-1]: 
        return True 
    else: return False

Upvotes: 0

Related Questions