Learning nested for loops in Python with Pig Latin translator I've been trying to learn Python for a bit now. I've taken a few courses, but I've found that I've been going about them wrong and had allowed them to "hold my hand" too much. I'm trying to build projects on my own and thought I would start off small. My third or so project was this Pig Latin translator and I wanted to get my head wrapped around nested for loops.

I know this code is super sloppy and I would love to have some feedback on how to make it more efficient or if there are any glaring mistakes I missed.

vowels = 'AaEeIiOoUuYy'
sentence = raw_input("Enter word to be translated: ")
pig_word = ""
# breaks up the words in the string and puts them into a list
sentence_list = sentence.split()
pig_list = []

def pig_latin_trans():
    global pig_word, pig_list
    for item in sentence_list:
        count = 0
        for letter in vowels:
            if letter == item[0]:
                pig_word = str(item) + "way"
                pig_list.append(pig_word)
                break
            if letter != item[0] and count &lt; len(vowels):
                count += 1
            if letter != item[0] and count == len(vowels):
                pig_word = str(item[1:]) + str(item[0]) + "ay"
                pig_list.append(pig_word)
    print " ".join(pig_list)

pig_latin_trans()
It's nice that you created a function.  Unfortunately, your function accepts no parameters and returns no values.  Rather, it refers to the global sentence_list as its input, and prints the output as a side-effect.  Worse, it uses global variables pig_word and pig_list, which should definitely have been local variables instead.  (Call this function a second time, and you'll have a mess!)



Your variable naming is poor, here:


# breaks up the words in the string and puts them into a list
sentence_list = sentence.split()



… and here:


for item in sentence_list:



For clarity, those should be words = sentence.split() and for word in words:, respectively.  You could then drop the comment.

Since vowels is a constant, it should be named VOWELS instead.



The for letter in vowels loop is problematic.  You just want to see whether the first letter of the word is a vowel.  The way to do that should be

if word[0] in VOWELS:




Suggested solutions

VOWELS = 'AaEeIiOoUuYy'

def pig_latin_trans(sentence):
    pig_list = []
    for word in sentence.split():
        if word[0] in VOWELS:
            pig_list.append(word + "way")
        else:
            pig_list.append(word[1:] + word[0] + "ay")
    return " ".join(pig_list)

print(pig_latin_trans(raw_input("Enter words to be translated: ")))


The loop to build pig_list could be more elegantly expressed using a generator expression.

def pig_latin_trans(sentence):
    return " ".join(
        word + "way" if word[0] in VOWELS else
        word[1:] + word[0] + "ay"
        for word in sentence.split()
    )