3
votes

I tried this -

x=[2,3,4,7,9]
count=0
for i in x:
  if i%2:
    count=count+1
print count

why the count is 3 instead of 2, as i%2 is satusfiying only for "2 and 4"?

3
Open up the Python console, and do 4 % 2, what is the result? Then do 3 % 2, what is the result? Now which of the results would be considered "true"? The modulo operator returns the remainder after a division. If the division is even (like in 4 % 2) then there is no remainder, the result is 0. - Some programmer dude

3 Answers

3
votes

The modulus of 2 over 2 is zero:

>>> 2 % 2
0

So 2 % 2 produces 0, which is a false value, and thus the if statement doesn't match.

On the other hand, the modulus of 3 over to is one:

>>> 3 % 2
1

1 is a non-zero integer, so considered true.

In other words, the if i%2: test matches odd numbers, not even. There are 3 odd numbers in your list.

Remember, modulus gives you the remainder of a division. 2 and 4 can be cleanly divided by 2, so there is no remainder. The if test checks for a remainder.

1
votes

If the Boolean expression evaluates to true(it can be any non zero value), then the if block will be executed.

You can achieve to get all even number counts by updating code as follows :

x=[2,3,4,7,9]
count=0
for i in x:
  if i%2 == 0 :
    count=count+1
print count
0
votes

Why you are having this problem is because you have signed told your code what to expect when your if statement meets a condition. As pointed out by @Harsha, to satisfy the condition for even numbers, it should be:

x=[2,3,4,7,9]
count=0
for i in x:
  if i%2 = 0:
    count=count+1
print count

If you want to get the odd numbers:

x=[2,3,4,7,9]
count=0
for i in x:
  if i%2 > 0 :
    count=count+1
print count