为什么如果没有中断,这段代码会继续返回我的输入?

Why if there is no break this code keep returning my input?

谁能帮我理解为什么如果我不把 break 放在那里,代码会给我多个输出。例如:

In : myfunc('abogoboga')

Out : 'aBoGoBoGaaBoGoBoGaaBoGoBoGaaBoGoBoGaaBoGoBoGaaBoGoBoGaaBoGoBoGaaBoGoBoGaaBoGoBoGa'

def myfunc(*args):
    output = []
    for strg in args:
        for char in strg:
            for i in range(len(strg)):
                if i % 2 == 0:
                    output.append(strg[i].lower())
                else:
                    output.append(strg[i].upper())
            break
    return ''.join(output)

但是,在像上面那样输入 break 之后:

In : myfunc('abogoboga')

Out : 'aBoGoBoGa'

您的嵌套 for 循环完成同样的事情。 for char in strgchar 分配给 strg 中的每个字符,但您从未使用过它。相反,您再次迭代 strg,它与 break 一起工作的原因是,如果您在执行 for char in strg 的一个循环后中断,您会将 for 循环变成一个简单的语句.一种更简单的方法是删除 for char in strg:

def myfunc(*args):
    output = []
    for strg in args:
         for i in range(len(strg)):
             if i % 2 == 0:
                 output.append(strg[i].lower())
             else:
                 output.append(strg[i].upper())
    return ''.join(output)