What Does X % 2 ==0 Mean? [Closed]

I'm sure it's very basic and I should understand it, but I don't!

I'm given this to do:

Loop through and print out all even numbers from the numbers list in the same order they are received. Don't print any numbers that come after 237 in the sequence.

This is the program i have for these numbers.

numbers = [
    951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 
    615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 
    386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 
    399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 
    815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 
    958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 
    743, 527
]

# your code goes here
for x in numbers:
    if x % 2 == 0:
        print x
    if x == 237:
        break

I get the right solution and everything right but I have no idea what the ==0 is there for. The only reason I used it is because it was used in the other example during the lesson before the practice!

4

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 the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*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].

4

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.

5

== 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".

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest