Python 2.7: Exercise: PygLatin Translator

I was reviewing python tutorials in codeacademy which I really recommend as a great beginning to get yourself familiar with any language. These guys have got some interactive tutorials and exercises which makes it pleasure to start with something new.

Of course you will need some broader sources and reference informaiton after completing the tutotrials in codeacademy. So I got this exercise from codeacademy - let’s see how we can solve it.

Problem:

Now let’s take what we’ve learned so far and write a Pig Latin translator.

Pig Latin is a language game, where you move the first letter of the word to the end and add “ay.” So “Python” becomes “ythonpay.” To write a Pig Latin translator in Python, here are the steps we’ll need to take:

  • Ask the user to input a word in English.
  • Make sure the user entered a valid word.
  • Convert the word from English to Pig Latin.
  • Display the translation result.

Solution:

def convert_to_pig_latin(word): first = word[0]

# appending the string with the first letter and "ay"
new\_word = word + first + "ay"

# removing the first character as it's already appended to the end
new\_word = new\_word\[1:len(new\_word)\]
return new\_word

input = raw_input(“Enter a word: “)

input should not be blank, and should consists of alpha characters

if not (len(input) > 0 and input.isalpha()): print “This is not a word!” else: translated = convert_to_pig_latin(input) print “The word %s is translated to pig latin: %s” % (input, translated)