Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...