0

Could anyone help me to understand why if I didn't put break there, the code give me multiple output. For example:

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)

but, after putting break as above:

In : myfunc('abogoboga')

Out : 'aBoGoBoGa'

Community
  • 1
  • 1

1 Answers1

0

Your nested for loops accomplish the same thing. for char in strg is assigning char to each character in strg, but you never use it. Instead, you iterate over strg again, and the reason it works with the break is that if you break after performing one loop of for char in strg, you are turning the for loop into a simple statement. A simpler way of doing this is removing 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)
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76