Make alternate letters capital

  • A+

I want to make alternate letter capital for any given word. So I create below function. But the issue is that it doesn't return any value. Rather I feel, it goes in infinite loop.

def farrange(word): finaloutput = '' i = 0 for i in word:     if i%2 == 0:         finaloutput = finaloutput + word[i].upper()             else:                     finaloutput = finaloutput + word[i].lower()         i = i + 1    return finaloutput 

I know there are other ways to solve the problem. I used another way of tuples unpacking. But I want to know why is it happening?


You are using i as both a loop variable (incrementing integer) and a variable to hold a string. That is why it isn't working. Try this fixed code of the function:

finaloutput = '' i = 0 for e in word:     if i%2 == 0:         finaloutput = finaloutput + e.upper()             else:                     finaloutput = finaloutput + e.lower()         i = i + 1    return finaloutput 

You could also do a list comprehension:

''.join([e.lower() if c%2 else e.upper() for c,e in enumerate(a)]) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: