6. is_prime. Help!


#1



Link to exercise I am stuck at:
https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


Error message I recieve:
Oops, try again. Your function fails on is_prime(2). It returns None when it should return True.


I have spent forever trying to figure out what is going on. Searched forum for other people who are having trouble but I just don't get why it's not working. I don't understand why it returns none instead of either false of true!


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


#2

There is one branch (it can execute different branches due to conditions in if-statements and loops) in your code which doesn't encounter a return statement, it'll return None


#3

Try looking over this code and review the steps being taken to get the desired solution.
- First you want to check if the number is less than 2 and if so return false. If not go to the next step.
- Once the first step is passed create a for loop to run the numbers between 2 and the input(x) checking if x is equally divisible by "n". If this is true the loop will print out false. If the first statement is false the loop will move to its else statement by returning True

def is_prime(x):
    #if x is less than 2 return false if not continue with next step
    if x < 2:
        return False
    else: 
        '''check if x is divisible evenly by "n" 
          and if so return false. If not return true'''
        for n in range(2, x - 1):
            if x % n == 0:
                return False
        else: 
            return True

#4

Well 2 % range(2, x - 1) = 0 because 2 / 2 = 2 and 2 / 1 = 1.
I just added an elif saying that if the number == 2 then it is prime.
Also your else needs to be in line with your for loop and that break is unnecessary.


#5

i think "for n in range(2,x-1)" is wrong and the last "else" should be deleted.
because "range (1,3) " means 1,2 ,it doesn't include 3;
in the loop,when first loop,there is output,but the loop doesn't finish. and i think add "return true" to the first "else" .

i hope this can help you.


#8

You double indented your else


#9

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