Search code examples
pythonfor-loopif-statementor-operator

Why does the "or" operator in the if statement not work?


Why does the if statement in the for loop not work properly? "0,1" is still being returned as True although it is smaller than 2. Code is a bit sloppy, sorry.

def isprim(n):
    for i in range(2,n-1):
        if n % i == 0 or n < 2:
            return False
    return True

for i in range(50):
    if isprim(i):
        print(i)

Output is:

0 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47


Solution

  • When n = 0, n = 1 or n = 2, the function does not execute the loop, because the loop's range starts from 2, thus the function skips the loop and returns True.