Help please on the is_prime function


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


it says other numbers don't work, I don't really get what the second step of the instructions is saying. It says from each number n from 2 to x - 1, test if its evenly divisible by n? If so where would I call n? The error message was that: is_prime returned True, when it's supposed to return false. I logically went through that, substituted x for 2. And when it gets to the second if statement it's not running the code because 0 is not greater than 1. This is obviously a flaw in my idk formula, so can anyone explain what the second step means, or point me in the right direction. I know this is supposed to be the challenging section, but I'm only in geometry and know algebra one. So you can call me stupid, I know I'm stupid. but can you atleast explain it please. or give a tip


def is_prime(x):
    if x <= 2
        return False
    elif x % 2 > 1:
        return False
    else: 
        return True


Is_prime
#2

It doesn't get to the second condition for x=2, because the first condition is satisfied.
Checking three conditions is also nowhere near enough to determine whether an arbitrary number is prime.
All you need to know math-wise to understand what a prime number is, is division, and the algorithm you're meant to implement is called trial-division since what it does is to try to divide the number in order to determine whether it's divisible by anything other than 1 or itself which is the definition of a prime, with the addition that it needs to be positive


#3

There's no need to call yourself stupid.
If anything, identifying why you're stuck and describing the situation shows otherwise.


#4

def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x>2:
l=range(2,x)
for i in range(2,x):
if x % i == 0:
return False
else:
return True

print is_prime(9)

Im getting True for this, could you please point out my mistake?


#5

9 > 2, so this part of your code executes:

for i in range(2,x):
	if x % i == 0:
		return False
	else:
		return True

In the first iteration here your code starts with checking 9%2, gets !=0 and goes to else hitting True there. The rest of the range does not get checked. You can see it for yourself if you run this:

for i in range(2,x):
	print i
	print x % i
	if x % i == 0:
		return False
	else:
		return True

You need else to execute only after the first condition gets checked for all numbers in range(2,x).


#6

Thank you!! This really helped


#7

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