Palindrome, Python Programming

words

A palindrome is a word that reads the same backwards as it does forwards. An example of a palindrome is Anna, refer and racecar.

I will take you through this simple little program step by step. The complete program is available at the end.

A while loop is required in order to keep the program functioning.  Otherwise it would close after the first input.

 

var = 1   # you can use any arbitrary word or number. I just picked 1

while var == 1:    # this just keeps the while loop running

 

Next we take input from the user. This is stored in the variable word. Don’t forget to indent the code because it comes under the while loop.

    

            word = input(” Please enter a word “)

 

This is where it becomes interesting. We assign the variable word (where we just stored the user input) to a new variable called reverse. However, we use -1 to store the input backwards.

 

word[::] is the same as just printing the contents of variable word. Putting -1 with the two :: reads the input stored in the variable backwards, so;

 

                reverse = word[::-1] 

 

We can now use an if statement to evaluate whether the input entered by the user is in fact a palindrome.

 

              if word == reverse: # if the two words are the same

                                print(word + ” is a palindrome, go again… “)                       

                else:      

                                print(“sorry ” + word + ” is not a palindrome, try again “)

 

The Complete Program as follows;

var = 1

while var == 1:            

                word = input(” Please enter a word “)   

                reverse = word[::-1]  

                if word == reverse:

                                print(word + ” is a palindrome, go again… “)          

                else:     

                                print(“sorry ” + word + ” is not a palindrome, try again “)

 

And that’s it, the program will tell you whether it is a palindrome or not!

Check out http://www.unleashthepython.com for more

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s