Is_prime


#1


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

I get "Your function fails on is_prime(4). It returns None when it should return False."

Unless I'm missing something, this code should divide 4 / 2 and find it's not a prime. I don't understand why it returns "None".

#Define a function called is_prime that takes a number x as input.
#For each number n from 2 to x - 1, test if x is evenly divisible by n.
#If it is, return False.
#If none of them are, then return True.

x=raw_input("Number?")
x=int(x)

def is_prime(x):
    if x==1 or x==0:
        return False
        
    if x==2 or x==3:
        return True
    
	if x>3:
		for n in range(2, x-1):
			if x % n == 0:
				return False
	else:
	    return True

is_prime(x)


#2

Should you be using 'elif' statements instead? One if/elif/else statement is all I needed. You might want to look at the hint too, right now, your code isn't excluding all values < 2.


#6

This simplified version (as suggested in the exercise) does not require more than two if statements. One at the beginning,

if x < 2: return False

and one in the loop:

if x % n == 0: return False

Scale back your code to the simplest form.


#7

x=raw_input("Number?")
x=int(x)

def is_prime(x):
if x<2:
return False
else:
for n in range(2, x-1):
if x % n == 0:
return False
else:
return True

is_prime(x)

I keep getting "Oops, try again. Your function fails on is_prime(2). It returns None when it should return True."


#8

This would indicate an indentation problem. Suggest remove the else: and move return True to the left so it lines up with the first line of the function.


#10

It works! Thank you :smiley:


#13