Is_prime


#1
def is_prime(x):
  if x < 2:
    return False
  if x == 2:
    return True
  for n in range(2, x):
    if x % n == 0:
      return False
  else:
      return True

This code is for finding prime numbers. What I don’t understand is the last 5 lines. Why do we use a for/else instead of indenting else for a if/else?

My reasoning is that the if/else says that if there is no remainder then it is NOT a prime number, otherwise (else) it is.


#2

9 is not a prime number, the first value tested by the loop is 2, lets fill in the if condition:

if 9 % 2 == 0:

which evaluate to false, so if you had if/else the else clause while run, return True, which will end the function, and the function would determine that 9 is a prime number (while its not)

that is why we use for/else, we need to verify that x is not divisible by all numbers in range 2 till x (exclusive x of course)


#3

Pick a prime and non-prime number for x, (7 and 12 are good) and then manually check if they are prime, followed by reading the code and checking that it says to do the same actions.

Try the same thing with the other indentation.

You’ll either answer your own question or find that there is something that you do not understand in your code - in which case either replace it with something that you do understand or learn about that something.

Yes, you’re supposed to know what each and every thing there does, and in almost all code that you write (You’re TELLING the computer what to do, you better know what you’re saying, if you don’t know then nobody else does either, so who then decided what should happen?). So if there’s anything that isn’t true for then you’ve found the cause of confusion and you’ve also found what you need to look up.

That code doesn’t use for-else, it’s the result of playing around with indentation and ending up with something that by accident is valid syntax and seems to do the right thing (it misses the point of for-else so anyone who knows what for-else does can spot that this was written by shuffling things around without a plan)


#4

^ Can you explain your last paragraph? How would you use for/else in this case if I am not using it correctly?


#5

What makes you say it’s useful here? Start by learning what it does, or simply don’t use it.

You wouldn’t grab a paper towel and assume it’s useful as a hammer. You’d either figure out what a paper towel does, and probably not at all use it as a hammer, or you’d consider what a hammer is and look for something hard and heavy, preferably something that you can swing a bit.

Whenever you write something, make an argument for why that is correct. And if you don’t know what to use, then consider what you need and look for something which has those properties.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.