People, including myself, have already pointed out your programming error. Here is an alternative one-liner solution to your problem using a generator expression and a ternary conditional operator:
def myfunc(word):
return "".join(w.upper() if i%2 else w.lower() for i,w in enumerate(word))
enumerate
will return a tuple of the form (index, value)
for each item in the iterable. In this case, the iterable is the string word
.
At each step in the iteration, we check to see if the index i
is odd.
i%2
will return 0
for even numbers and the if
statement will evaluate to False
.
- Likewise, it will evaluate to
True
for odd numbers.
Respectively, we call lower()
and upper()
on the current character w
.
Finally we use str.join
to concatenate all the individual letters back together. Here we join the characters using an ""
with is the empty string.