Skip to content Skip to sidebar Skip to footer

If Statement With Modulo Operator

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

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

Solution 3:

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

Post a Comment for "If Statement With Modulo Operator"