How does this code work?

PURPOSE OF THE CODE: Following code is a function which takes a string and returns a string in which even indexed words are capital and odd indexed words are lower case

def myfunc(word):
    index = 0
    result = ''

    for letter in word:
        if index % 2 == 0:
            result += letter.lower()
            result += letter.upper()
        index += 1
    return (result)

Can someone explain to me the role of fourth last line (index+=1) in the above code?
I want to know because when i take it out, i do not get the desired result.
I have a feeling it allows for the loop to take place but am not sure

hi @python_newbie
as my understanding of the problem, for each word you need to check if its position is odd or even, but I think your code is iterating over the all the characters in the giving string not the words, hers a pseudo-code :

index = 0
accumulator = ""
foreach word in words do
        if index is even
                accumulator += toCapital(word)
                accumulator += toLower(word)
        increment index by 1 for the next word (index+=1)      
return accumulator

try implementing it in your language (python)

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


1 Like

Thanks. I’m new here:)

Before you try to reason about this line, I think you need to know why the variable is there and what it is for.

To solve your challenge, you need to compare the values of current index. Python’s for loop structure doesn’t explicitly make that value available and so, the programmer has to do this manually. If the value of index wasn’t updated there on the last line, it would remain as 0, and the test for evenness would always be true, and your result would be IN ALL CAPS! :wink:

I highly recommend checking out Phillip Guo’s Python Visualizer! It lets you step through each line of code and see a visualization of what’s going on. It also works with other languages such as C and C++, Java, JavaScript, TypeScript, and Ruby.


Welcome! I’m not new, but I’m not here very often

This was helpful and exactly what i was asking for :+1:

Awesome! Glad I could help

of course, your absolutely correct, you need to increment the index each iteration
but in @python_newbie’s PURPOSE OF THE CODE, you need to check words (even / odd indexed) in a giving string, not letters.
I think for letter in word iterate over each letter in word.

Thanks @Arekkusu44! I didn’t know that excellent Visualizer as well! It helps me a lot! :+1: