0

I have a piece of code:

def is_prime(x):
    if x >= 2:
        for n in range(2,x):
            if not ( x % n ):
                return False
    else:
        return True

I am confused by the line if not ( x % n ):

I know % is module and gives the remainder. I'm confused because I thought there had to be something for it to compare to like: if x%n == y:

Can someone explain what exactly if not ( x % n ): means?

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Because of falsy values in any programming language, in this case for python: https://stackoverflow.com/a/39984051/3558900 as you can see, 0 is a falsy value. – Randall Valenciano Jan 22 '18 at 22:35
  • See https://stackoverflow.com/a/39984051/2285236 – ayhan Jan 22 '18 at 22:35
  • 1
    If `x` is divisible by `n` the term `x % n` will return `0` and `not 0` in python is evaluated to `True` - this will cause the function to return `False` since `x` is not a prime. And you're right you could substitute `if not ( x % n )` with: `if x % n == 0` – Nir Alfasi Jan 22 '18 at 22:36
  • so is the default 0 if your do not specify a number for it to be equal to? – Katherine Gibson Jan 22 '18 at 22:42
  • @KatherineGibson no. Truth value testing does not require equality testing, i.e. `a == b`. Indeed, in Python, **any** object can be evaluated for a truth value. – juanpa.arrivillaga Jan 22 '18 at 22:45

0 Answers0