Categories

# Check if Palindrome – Python

Another one of these challenges – this one is just too easy.

## The Challenge

Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar”

## The logic

Since palindromes are the same whether they are spelled backwards or not, we can compare the two strings, the normal one and the reversed one (using the same loop as the reverse string challenge).

If they are both exactly the same, we have a palindrome!

However, we might get a false negative if there is an upper case letter. Therefore, it might be a good idea to change all letters to lowercase.

## The Code

```# the string
str_the_raw_word = raw_input('Enter word: ')

# change all letters to lowercase
str_the_word = str_the_raw_word.lower()

# find the length of the word
int_word_len = len(str_the_word)

# reverse word as list
list_rev_word = []

# loop through each letter
for i in range(1,int_word_len+1):

# reverse the possition
int_rev_pos = int_word_len - i

# now move to list
list_rev_word.append(str_the_word[int_rev_pos])

# from list to string
str_rev_word = ''.join(list_rev_word)

# now compare both strings
# if its the same then we're good
if str_rev_word == str_the_word:
print 'Yo Mr White, "%s" be a palindrome and s#@t!' % str_the_raw_word

# if not the same then there's problem
else:
print 'Nope, you suck!'
```

so if we run it using the word ‘RaceCar’ as an example

```\$ python _palindrome.py
Enter word: RaceCar
```

We should get the following output.

```Yo Mr White, "RaceCar" be a palindrome and s#@t!
```

and if we run it again using the word ‘what’ as an example

```\$ python _palindrome.py
Enter word: what
```

We should get the following output.

```Nope, you suck!
```