-1

I'm trying to make a program that checks if user's input word is a palindrome and asks words until the input is a palindrome. My problem is that I can't get my program to print anything and could use some tips to fixing it. This is what I have so far:

def palindrome(word):
    while True:
        word=input("Enter a word: ")
        for i in range(len(word)):
            if word[i]==word[(i+1)*-1]:
                print(f"{word} was a palindrome!")
                return True
            else:
                print("not a palindrome")
                return False
  • While there are issues with your function, your problem description seems off. It prints `'bob was a palindrome!'` just fine for me. – timgeb Jul 05 '21 at 13:51
  • Did you actually call this function somewhere in your script ? Defining it not enough. Also the word parameter is useless, as you overwrite with input. – May.D Jul 05 '21 at 13:55

2 Answers2

1

You have easier ways to check if a word is a palindrome like : word == word[::-1]. (Is the word equal to itself written in reverse)

def palindrome():
    word=input("Enter a word: ")
    if word == word[::-1]:
        print(f"{word} was a palindrome!")
    else :
        print("not a palindrome")
        

Anyway, to improve your program you can remove the while True boucle that isn't useful here, you do not need word as an argument since you define it in your function. Then you need a variable that can "remember" if a letter is not equal to the letter at the opposite position.

def palindrome():
    word=input("Enter a word: ")
    isPalindrome = True
    for i in range(len(word)):
        if word[i] != word[(i+1)*-1]:
            isPalindrome = False
    if isPalindrome:
        print(f"{word} was a palindrome!")
    else:
        print("not a palindrome")

palindrome()

They are many ways to improve this program to make it shorter / smarter but that should be a good place to start with.

Youenn FS
  • 76
  • 2
0

You have a problem with your function.. and you did not even make it a call so how it will work try this


def palindrome():
    while True:
        word=input("Enter a word: ")
        for i in range(len(word)):
            if word[i]==word[(i+1)*-1]:
                print(f"{word} was a palindrome!")
                return True
            else:
                print("not a palindrome")
                return False
palindrome()

Kenit
  • 137
  • 1
  • 1
  • 13