Is_prime: what happens when x=2?


My code works fine but I think it shouldn't... If x = 2 it should return False but 2 is a prime number???!!! What am I missing?

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

Replace this line with your code.


Hello :slight_smile:

So we assume that x = 2. Your function starts with the if, let's check the condition:

2 >= 2
=> True

so we are inside the if block.

Now we have a for loop. Let's check the result of range(2, x):

range(2, 2)
=> []

so block of for loop will not be executed, so we go to the else block.

else block contains only one statement - return True. So, according to your function 2 is a prime number, everything is correct :slight_smile:


Thank you for your reply! I just thought that if my range(2,2) started at 2 but ended at 1 (x-1) the code would generate an error...


You're very welcome :slight_smile:

Python does not like to throw errors. So even something like range(10, 1, 3) will return an empty list.


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