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!