Python Forum
Supposed to print out even numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Supposed to print out even numbers
#1
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
Reply
#2
The code is checking if the counting variable num is even instead of a value of a item in the list
Reply
#3
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=" ")
Reply
#4
Okay, thanks. It was bugging me because if you run it with list1 = [10, 21, 4, 45, 66, 93] it works fine.
Reply
#5
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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Print max numbers in a list jimmoriarty 1 266 Sep-25-2020, 07:29 AM
Last Post: DPaul
  Is there a way i print odd and even numbers separately? spalisetty06 5 438 Jul-21-2020, 06:48 PM
Last Post: spalisetty06
  first k non prime numbers print bsrohith 7 3,284 Jun-20-2019, 10:48 AM
Last Post: arycloud
  my function is stuck on loop - even when it not supposed to be korenron 2 734 May-26-2019, 12:31 PM
Last Post: korenron
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 885 May-09-2019, 12:19 PM
Last Post: Pleiades
  Why can't I print numbers in Python? skrivver99 2 1,081 Nov-04-2018, 09:47 PM
Last Post: snippsat
  How to test a function that is supposed to return NoneType? w0mb4rt 1 1,652 Feb-17-2018, 07:38 PM
Last Post: Gribouillis
  Print list from splitted range of numbers prashant8530 1 1,339 Sep-04-2017, 08:03 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020