Skip to content
Advertisement

How to understand this loop program in Python

I’m trying to polish my Python skills and this made me confused. Here’s the code:

greeting = 'Hello!'
count = 0

for letter in greeting:
    count += 1
    if count % 2 == 0:
        print(letter)
    print(letter)

print('done')

I don’t understand what the count does.

Advertisement

Answer

Let’s comment up the code with explanations of what each line does and then examine the output.

# assign the string 'Hello!' to the name greeting
greeting = 'Hello!'
# assign the number 0 to the name count
count = 0

# assign letter to each character in greeting one at a time.
# in the first run of the loop, letter would be 'H', then 'e',
# etc.
for letter in greeting:
    # add one to count. count starts at 0, so after this line
    # on the first run of the loop, it becomes 1, then 2, etc.
    count += 1
    # use the modulo operator (%) to get the remainder after
    # dividing count by 2, and compare the result to 0. this
    # is a standard way of determining if a number is even.
    # the condition will evaluate to True at 0, 2, 4, etc.
    if count % 2 == 0:
        # when count is even, print letter once followed by a
        # new line. note that to not print a new line, you can
        # write print(letter, end="")
        print(letter)
    # print letter once followed by a new line regardless of the
    # value of count
    print(letter)

# print 'done' followed by a new line
print('done')

So, based on all that, what should we expect the output to be? Well, we know that every character of greeting will be printed in the last line of the loop. We also know that every even character of greeting will be printed twice, once inside the if block, and once at the end of the loop. Finally, we know that “done” will be printed after the loop is complete. Therefore, we should expect the following output:

H
e
e
l
l
l
o
!
!
done
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement