Chris Summerhays
Chris Summerhays

Reputation: 37

simple for loop needing explained

I know this is going to sound silly but I cannot for the life of me figure out the logic behind how this for loop returns 13,11,9,7.

    for i in range(13,5,-1):
        if i % 2 != 0:
            print i

I know the first value is the number it starts with, the second is where it stops, and the third being the steps it takes. The "if i % 2 !=0:" is what is throwing me off. Can anybody explain what is happening for me?

Upvotes: 2

Views: 106

Answers (3)

Bill the Lizard
Bill the Lizard

Reputation: 405715

if i % 2 !=0

That line means "if the remainder after dividing i by 2 is not equal to 0," so it's checking to see if i is odd. The for loop is counting down by 1, but the if statement skips printing the even numbers.

Upvotes: 2

Miki Tebeka
Miki Tebeka

Reputation: 13850

% is the modulo operator. From the 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.

Upvotes: 3

mgilson
mgilson

Reputation: 309831

the first bit is the range(13,5,-1) which just counts backwards from 13 to 6. The next bit is i%2 != 0. i%2 == 0 is equivalent to saying if even, or "if this number can be divided by 2 with no remainder", so your statment is saying "if odd" (which is obviously the same as "if not even").

Basically, the loop is printing odd numbers starting at 13 and decreasing down to 6 (but 6 is even, so it doesn't get printed)

Upvotes: 3

Related Questions