简体   繁体   English

对于第一种情况后的循环停止

[英]For loop stops after 1st case

I have a for loop that goes through each word in a string and returns a modified string. 我有一个for循环遍历字符串中的每个单词并返回一个修改过的字符串。

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? 我怎样才能解决这个问题?

return immediately leaves the function, even if you are only on the first pass through your for loop. return立即离开函数,即使您只是第一次通过for循环。

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'

Increase the indention of the else block as following: 增加else块的缩进如下:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM