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


#1



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


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


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


#2

And what's the problem? Your function returns None for 2, and obviously, it should return True.

Why it returns None? Let us assume that x = 2.

Is 2 > 1? Yes, so now we are in the if block.

This code -> for n in range(2,x) with x = 2 is for n in range(2,2). This basically means "set n to 2 and execute block of code as long as n is lower than 2 and increment n by 1 after every iteration". So... block of this for will not be executed, not even once, because 2 is not lower than 2, right?


But the problem is kind of deeper, let us assume now that x = 5.

Is x > 1? Sure. So again, we are in the block of if.

for n in range(2,5):
  if (5 % n == 0):
      return False

Let us check what happens in the for loop:

# n = 2
5 % 2 = 1

# n = 3
5 % 3 = 2

# n = 4
5 % 4 = 1

So this code will not return False, but it also does not return True. So it returns nothing, None.


In some place in your code you need to return True.


#3

Hey jkm345, here are the fixes I did for your code to make it work. If you have questions let me know

def is_prime(x):
    if x == 2: # I put this one first to get away of it, as 2 is a Prime
        return True
    elif x > 1: #as we have gotten away from 2 at the IF section, we can now use x > 1 here, like in your code
        for n in range(2,x):
            if (x%n ==0):
                return False
        else: #this else is for every n%x != 0, so a Prime number
            return True
    else: #this else is for every x < 1
        return False

#4

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