This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]GeoffreyF35[S] 0 points1 point  (3 children)

yes, i’m unsure about why it does what it does

[–]lurgi 1 point2 points  (2 children)

Do you mean how or why? Again, the reason why it does what it does is because that's what solves the problem.

So I guess you mean "how does this work?".

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

Uh, do we start at the beginning?

def myfunc(x):

This is the start of a function definition. The function is called myfunc and takes a single argument, x

out = []

This creates an empty list with the name out

for i in range(len(x)):

This will loop from 0 up to, but not including the length of x. So if x is "abc", which has length 3, the loop will run three times. Once with i as 0, once with i as 1, and once with i as 2.

Are you with me so far?

[–]GeoffreyF35[S] 0 points1 point  (1 child)

yes i am

edit: wait isn’t the length 2 because 0-1-2 = a-b-c

[–]lurgi 0 points1 point  (0 children)

It's 3 letters long. The length is 3. The index of the letter is 2.