Search code examples
python-2.7explain

Explain this bit of code to a beginner


for x in xrange(12):
    if x % 2 == 1:
        continue
    print x

i know what it does, but the language doesn't make sense to me. In particular the second line is where i am lost.


Solution

  • if x % 2 == 1 means "if x modulo 2 equals 1".

    Modulo (or mod) is the remainder after division. So, for example:

    3 mod 2 = 1
    12 mod 5 = 2
    15 mod 6 = 3
    

    For x mod 2, you're there's a remainder if and only iff x is odd. (Because all even numbers are divisible by two with 0 remainder.) Likewise, odd numbers will always have a remainder of 1.

    So x % 2 == 1 returns true if x is odd.