Why is my code below giving me wrong results? When I give it numbers like 2 and 3, it says they're not prime numbers. Only some numbers work but for the most part it gives wrong answers.
def prompt_input(input_msg, error_msg):
while True:
userinput = input(input_msg)
try:
integer = int(userinput)
if integer > 1:
return integer
print(error_msg)
except ValueError:
print(error_msg)
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
primenum = prompt_input(
"Give an integer that's bigger than 1: ",
"You had one job"
)
if check_prime(primenum):
print("This is a prime.")
else:
print("This is not a prime.")
CodePudding user response:
First issue: Your for loop returns after one iteration, so the correct return logic would be:
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
However you are implementing this incorrectly as well, the loop needs to iterate up to the sqrt of the number.
def check_prime(number):
for i in range(2, int(sqrt(number)) 1):
if number % i == 0:
return False
return True
Hope this helps!
CodePudding user response:
Need to unindent the return True
.
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True