如果声明与模运算符 [英] If statement with modulo operator

查看:143
本文介绍了如果声明与模运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过了 -

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

为什么计数是 3 而不是 2 ,因为 i%2 仅针对2和4进行satusfiying?

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

推荐答案

模数2大于2 0

>>> 2 % 2
0

所以 2%2 生成 0 ,这是一个假值,因此如果语句匹配。

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

另一方面,3的模数是1:

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

>>> 3 % 2
1

1 是一个非零整数,所以认为是真的。

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

换句话说,如果i%2:测试匹配奇数数字,甚至不匹配。您的列表中有3个奇数。

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

请记住,模数为您提供除法的余数。 2和4可以干净地除以2,因此没有余数。 如果测试检查余数。

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.

这篇关于如果声明与模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆