Swapping uppercase and lowercase in a string

I would like to change the chars of a string from lowercase to uppercase.

My code is below, the output I get with my code is a; could you please tell me where I am wrong and explain why? Thanks in advance

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    for word in words:
        if word.isupper() == True:
            return word.lower()
        else:
            return word.upper()  

print to_alternating_case(test)

Solution 1:

If you want to invert the case of that string, try this:

>>> 'AltERNating'.swapcase()
'aLTernATING'

Solution 2:

There are two answers to this: an easy one and a hard one.

The easy one

Python has a built in function to do that, i dont exactly remember what it is, but something along the lines of

string.swapcase()

The hard one

You define your own function. The way you made your function is wrong, because iterating over a string will return it letter by letter, and you just return the first letter instead of continuing the iteration.

def to_alternating_case(string):
    temp = ""
    for character in string:
        if character.isupper() == True:
            temp += character.lower()
        else:
            temp += word.upper()
    return temp

Solution 3:

Your loop iterates over the characters in the input string. It then returns from the very first iteration. Thus, you always get a 1-char return value.

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    rval = ''
    for c in words:
        if word.isupper():
            rval += c.lower()
        else:
            rval += c.upper()
    return rval    

print to_alternating_case(test)