pythonlogicdemorgans-law

Why, using "and" in a for loop and "or" in a while loop gives the same result?


I am trying to practice writing these loops, and I had an exercise which asked me to print numbers from 0 to 20 that aren't divisible by 3 or 5.
For the while loop, I wrote this code:

#solution with while

i = 0

while i < 21:
    i += 1
    if i % 3 == 0 or i % 5 == 0:
        continue
    print(i)

Whereas, for the for...in loop, I struggled because I found out that I needed to use and instead of or here.
The code is as follows:

#solution with for

for k in range(21):
    if k % 3 != 0 and k % 5 != 0:
        print(k)

Why did I have to change the logical operator?

In my head, the first rows of the two codes do the same thing, iterate a number from 0 to 20. So the condition, after these, should be equal for both the iterations used.
Can anyone explain to me what am I missing here?


Solution

  • This isn't a loop type problem, the issue is in using different equality operators in your conditions - != instead of ==.

    After changing or to and, the result stays the same because you've accidentally used De Morgan's second law (negation of disjunction):
    De Morgan's 2nd law


    Now, let's look at the code.

    In the while loop:

    In other words:


    Noe, let's check, what says the condition in the for...in loop:

    Looks like the same condition, doesn't it?
    As you noticed, in the In other words: paragraph, we've naturally used the negation of disjunction.

    To sum up, both programs for i / k lower than 21 print:

    0
    1
    2
    4
    7
    8
    11
    13
    14
    16
    17
    19
    

    If you still aren't sure, try to replace the conditions between loops:

    i = 0
    while i < 21:
        i += 1
        if i % 3 != 0 and i % 5 != 0:
            print(i)
    
    for k in range(21):
        if k % 3 == 0 or k % 5 == 0:
            continue
        print(k)