If statement with modulo operator

25,671

Solution 1

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.

Solution 2

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
Share:
25,671
Anonamous
Author by

Anonamous

Updated on June 01, 2020

Comments

  • Anonamous
    Anonamous almost 4 years

    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"?