# Is_prime

#1

this code gives me the error: Your function fails on is_prime(2). It returns None when it should return True.

First, what does is_prime(2) signify?

What I have tried to do was start with an if statement saying returning false if x<2 because a we know that one is not considered a prime number. I read on some other posts that since my for loop is in the range of 2 to x, two drops out and I can return it at the bottom in the last else statement.

number = input('num= ')
def is_prime(x):
if x < 2:
return False
else:
for num in range(2,x):
if x%num == 0:
return False
else:
return True
is_prime(number)

#2

This is my updated code. I realized that I had the if else statement in my for loop backwards, but now it fails on is_prime(3), which i know think i understand to be that when i plug three into my function, it returns the wrong thing.

number = input('num= ')
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for num in range(2,(x-1)):
if x%num == 0:
return True
else:
return False
is_prime(number)

#3

Adding the explicit line of if x==2... was a good idea, but you switched your true and false 'return's for if x%n == 0....

#4

Oh shoot, okay i switched my if-else statement inside the for loop back to the correct. This still gives me the same is_prime(3) error.

#5

A functions ends the moment a return keyword is reached, a return keyword is currently reached in the first iteration of your loop, so you loop only makes one iteration

For a number to be a prime number, num shouldn't be divisible by any number in range 2 (included) and num (excluded)

In other words, you only want to return True after the for loop has finished running

#6

So that means I should put my statement

else:
return True

outside of the for loop?

I am still a little confused because why would the loop need to finish running if we already know that it is prime?

#7

yes

the point of the loop determines if, for example 9, is not a prime number

#8

We don't know a number is prime without testing it for divisibility. Any number that is not divisible is accepted as a Prime.

Both 2 and any other number that survives the loop will return True at the very bottom, without an else.

return True

#9

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