0

I was working on a project Euler problem and found this code online:

a = 1
b = 2
s = 0

while b <= 4000000:
    if not b % 2:
        s += b
    a, b = b, a + b
print s

I am not entirely sure what if not b % 2: means and was wondering if someone would mind shedding some light on it for me.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • `if not b % 2:` = if the remainder of b / 2 is 0. – njzk2 Feb 21 '14 at 17:24
  • Did you read the Python documentation for what "not" means and what the % operator does? –  Feb 21 '14 at 17:28
  • `%` in most modern programming languages means modulus/remaining. You should look for the language documentation before asking such basic questions – phuclv Feb 28 '14 at 14:59

5 Answers5

3

From the docs:

The % (modulo) operator yields the remainder from the division of the first argument by the second.

e.g. 5/2 == 2.5 # or 2 remainder 1, 5%2 == 1

The only time a % operation will come out to 0 (which satisfies not x%y) is if it's evenly divisible. In other words, 4 % 2 == 0 because 2 divides 4 evenly.

In your code, it's saying:

while b is less than 4,000,000:
    if b is even:
        set s equal to s+b
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

The modulo % operator returns the remainder of the division of b per 2 (in your case).
So if not b % 2 is the same meaning that if b % 2 == 0: it checks if the number is even.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
0

b % 2 is the remainder after dividing by 2. So it will be 1 if b is odd, or 0 otherwise.

if not b % 2 can thus be translated to "if b is even"

offbyone
  • 1,183
  • 10
  • 17
0

Python interprets the value 1 as True and 0 as False:

>>> 1 == True
True
>>> 0 == True
False

The modulo operation x % y returns the remainder when x is divided by y. Therefore b % 2 will be 0 when b is even, and 1 when b is odd.

Combining all this together, the statement if not b % 2: corresponds to "if b is even".

Tetrinity
  • 1,105
  • 8
  • 20
  • 1
    No, that is not correct. In Python, every integer except for `0` evaluates to `True` in a boolean context. The behavior that you are seeing can be explained by the fact that `True` evaluates to `1` when it is interpreted as an integer (this is for historical reasons). –  Feb 21 '14 at 17:31
  • Ah, I see. I'll edit my answer to remove the confusion. – Tetrinity Feb 21 '14 at 17:34
-1

It's just a cute way of writing if b%2==0. The not operator when passed 0 will return True, and False given anything else.

C.B.
  • 8,096
  • 5
  • 20
  • 34
  • 1
    Fun fact: since Python is memory efficient and only produces pointers for small integers, you can do `if b%2 is 0` and freak out every programmer who has to maintain your code! – Adam Smith Feb 21 '14 at 17:28