Moh'd H
Moh'd H

Reputation: 247

function doesn't continue to loop

My function is acting a little bit weird.

def cow_latinify_sentence(sento):
''' Converting English to Cow Latin '''
    alpha = list("bcdfghjklmnpqrstvwxyz")
    finale = []
    worda = ""
    for word in sento.split():
        finale.append(word)
    for i in finale:
        if i[0].lower() in alpha:
            lista = list(i.lower())
            worda = worda.join(lista[1:] + [lista[0]]) + "oo"             
        else:
            return word + "moo"        
        return worda

When i run it with a sentence like:

cow_latinify_sentence("Cook me some eggs")

it returns: ookcoo. which is correct, however it doesn't loop around the other words in the sentence.

The function should perfectly return: ookcoo emoo omesoo eggsmoo

in addition to that, if i have a sentence like:

cow_latinify_sentence("aran likes his art")

it returns only the last element (artmoo) in the sentence being converted

so i'm guessing my issue is with the loops. i've tried changing positions of the return statement and got funny results as well.

Upvotes: 0

Views: 61

Answers (1)

MariusUt
MariusUt

Reputation: 752

When you return worda, you return the first word and then the function stops executing. Thus, it won't return anything else.

In Python, I would suggest you use something called list comprehension. For details on how it works, please search Google. I will give you an example of how to apply that to your case here.

alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
    if word[0].lower() in alpha:
        lista = list(word.lower())
        return lista[1:] + [lista[0]] + "oo"
    else:
        return word + "moo"

def cow_latinify_sentence(sentence):
    words = sentence.split();
    return [ cow_latinify_word(word) for word in words]

Upvotes: 2

Related Questions