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"?
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.
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
4 % 2, what is the result? Then do3 % 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 in4 % 2) then there is no remainder, the result is0. - Some programmer dude