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

69 views Asked by At

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

4

There are 4 answers

3
dev55555 On BEST ANSWER

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.

0
poh On

The for loop in isprim(n) is never entered since 2 is larger than both 0 and 1 for range(2, n-1). Therefore, return True is always executed for those cases.

0
Nathaniel Ford On

Game it out:

  • Loop from 0 to 49
  • Iteration 0 -> isprim(0)
  • Loop from 2 to -1 -> range(2, -1) is an empty list
  • return True
  • Iteration 1 -> isprim(1)
  • Loop from 2 to 0 -> range(2, 0) is an empty list
  • return True
  • Iteration 2 -> isprim(2)
  • From here on, n is always greater than or equal to 2.

So your issue is the for i in range(2, n-1). In the REPL:

>>> len(range(2, -1))
0
>>> len(range(2, 0))
0
>>> len(range(2, 1))
0
>>> len(range(2, 2))
0
>>> len(range(2, 3))
1

For those first few numbers that are prime, you're better off putting in explicit tests:

def is_prime(n: int) -> bool:
    if n not in [1,2]:
        for i in range(2, n-1):
            return False
    return True
0
J. Artola On

This is probably what you are looking for

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

    # Special case for 2
    if n==2:
        return True