-3

I'm writing a program that tells if this is a prime number from the input.

I'm trying to understand the logic of this code:

def prime_checker(number):
    for i in range(2, number):
        if number % i == 0:
          print("It's not a prime number.")
          break
        else:
          print("It's a prime number")
          break
n = int(input("Check this number: "))
prime_checker(number=n)

Previously, I did not put a break, which resulted with a lot of print statements being printer. So I googled, "how to end the loop in python".

Now, the code did not work as expected. For example, if I put 2, I get no results (nothing). If I put 87, it says it's a prime number (it's not).

Can someone explain what is wrong with the code? I know that the right solution would be:

def prime_checker(number):
    is_prime = True
    for i in range(2, number):
        if number % i == 0:
            is_prime = False
    if is_prime:
        print("It's a prime number.")
    else:
        print("It's not a prime number.")
n = int(input("Check this number: "))
prime_checker(number=n)

However, I do want to truly understand the logic and differences between two. Any thoughts? Many Thanks!

  • 1
    The first code checks if the number is divisible by 2 and then stops (claiming it's a prime number if it isn't divisible by 2). – mkrieger1 Feb 15 '23 at 14:48
  • 1
    See [Why does python use 'else' after for and while loops?](https://stackoverflow.com/q/9979970/6045800) . If you would only unindent the `else`, the first code will work – Tomerikoo Feb 15 '23 at 14:56

1 Answers1

2

You cannot know whether number is a prime before having checked all potential divisors. So you cannot expect to know the number is a prime before the loop has made all* iterations. You really need to be sure there is no integer divisor.

The opposite is true: you can know whether the number is not a prime before having tested all potential divisors, because you only need to find one divisor. As soon as you found it you know it is not a prime and don't need to continue looping. The second code could therefore be optimised by a break just following is_prime = False


* Well, you could know once i > sqrt(number). Fact is that the loop doesn't have to continue beyond that limit.

trincot
  • 317,000
  • 35
  • 244
  • 286