If statement with modulo operator

僤鯓⒐⒋嵵緔 提交于 2019-12-23 02:39:05

问题


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


回答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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/40481623/if-statement-with-modulo-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!