AspirationZ
AspirationZ

Reputation: 39

For loop stops after 1st case

I have a for loop that goes through each word in a string and returns a modified string.

However, the loop stops after the first word.

The summarized code looks like this:

def format(x):
    return x
def modify(string):
    for x in words:
        if statement:
            return x[v:] + x[:v] + "xx"
        else:
            return x + "xx"
def final(string):
    return format(modify(string))

The format function format what modify does, while the final function puts everything together. It works perfect for the first word in the string, but stops after that.

Current input and output:

>>>final("This is a test case")
>>>>Htisxx

What I want:

>>>final("This is a test case")
>>>>Htisxx isxx axx esttxx asecxx

Why does the loop stop? How can I fix this?

Upvotes: 0

Views: 155

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56644

return immediately leaves the function, even if you are only on the first pass through your for loop.

Instead, try

def first_vowel(word):
    for offset,ch in enumerate(word):
        if ch in "aeiou":
            return offset
    return 0

def modify_word(word):
    v = first_vowel(word)
    return word[v:] + word[:v] + "xx"

def modify(s):
    words = s.split()
    return ' '.join(modify_word(word) for word in words)

def format(s):
    return s

def final(s):
    return format(modify(s))

final("This is a test case")  # => 'isThxx isxx axx esttxx asecxx'

Upvotes: 3

Bishoy
Bishoy

Reputation: 725

Increase the indention of the else block as following:

def format(x):
    return x
def modify(string):
    for x in words:
        if statement:
            return x[v:] + x[:v] + "xx"
        else:
            return x + "xx"
def final(string):
    return format(modify(string))

Upvotes: -1

Related Questions