Python Forum
Supposed to print out even numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Supposed to print out even numbers (/thread-26993.html)



Supposed to print out even numbers - DallasPCMan - May-21-2020

When I execute this code:

list1 = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
num = 0
# using while loop
while (num < len(list1)):

    # checking condition
    if num % 2 == 0:
        print(list1[num], end=" ")

        # increment num
    num += 1
The output I am getting is:

1 9 25 49 81

I can't see why. The code comes from Geeks for Geeks website.

Thanks


RE: Supposed to print out even numbers - Yoriz - May-21-2020

The code is checking if the counting variable num is even instead of a value of a item in the list


RE: Supposed to print out even numbers - GOTO10 - May-21-2020

The reason for this is that your code is checking to see if num is even, when you really want to be checking list1[num]:

    # checking condition
    if list1[num] % 2 == 0:
        print(list1[num], end=" ")



RE: Supposed to print out even numbers - DallasPCMan - May-21-2020

Okay, thanks. It was bugging me because if you run it with list1 = [10, 21, 4, 45, 66, 93] it works fine.


RE: Supposed to print out even numbers - ndc85430 - May-21-2020

It works because the even items happen to be at even indices, so yeah, it's wrong.
Most importantly, do you understand now why your original solution was wrong?