python – What does x % 2 ==0 mean?
python – What does x % 2 ==0 mean?
x % 2
gives the remainder after the integer division (when dealing with only integers such as in this case, otherwise a common type) of x/2
. The %
is called the modulo operator. Of course when the remainder is 0, the number is even.
Docs:
The
%
(modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises theZeroDivisionError
exception. The arguments may be floating point numbers, e.g.,3.14%0.7
equals0.34
(since3.14
equals4*0.7 + 0.34
.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
if x % 2 == 0
checks if a number is even.
x % 2
is 1
when the number is odd, and 0
when it is even.
python – What does x % 2 ==0 mean?
== 0
means equal to 0 (zero). So if foo == 0:
means do the following if foo
is equal to 0, thus if x % 2 == 0:
means do the following if x % 2
is equal to 0.