lextragon
lextragon

Reputation: 21

Prime number function returns true instead of false

I'm currently learning Python with Codecademy. I am on exercise 6 called "is_prime". I wrote the function step by step from the instructions, but it returns True instead of False. Why?

Instructions:

Instructions

My code:

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

Error: Your function fails on is_prime(0). It returns True when it should return False.

Upvotes: 0

Views: 4442

Answers (4)

Umer iqbal
Umer iqbal

Reputation: 196

for 0 you should have extra if condition

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

Upvotes: 0

mastro35
mastro35

Reputation: 143

First of all: the else statement is completely useless, you can simply remove it. Beside, what's contained in the for loop doesn't run when you pass 0, 1 or 2 as a parameter because the loop starts from 2 and ends at the parameter's value - 1.

To get your function working you can change it as follows:

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

Dave

Upvotes: 2

E. Ducateme
E. Ducateme

Reputation: 4248

The following code should do what you want...

0 and 1 are never prime, so should always return False.

The number 2 should return True, but won't fit conveniently in the range() function, as described by other commenters.

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

Upvotes: 0

timgeb
timgeb

Reputation: 78690

The for loop never runs, because range(2, 0-1) is empty. This means that the else block executes (think of for/else as for/nobreak) which returns True.

Upvotes: 4

Related Questions