Is_prime returns none


#1



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

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

Hello,

I think I am blind or going crazy. I can't see how my functions returns none. For me if it takes 3 as input, it should return false.

Can anyone see what's wrong about this code?

Your help will be appreciated a lot! Thanks


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


#2

for n in range(2,x-1):

is same as

for n in range(2,2): # because x=3

so simply it'll not run. Outside of loop function returns nothing(none).


#3

Okay, thanks a lot! But the in the instructions, it says "For each number n from 2 to x - 1, test if x is evenly divisible by n."

So I suppose I have to check the input 3 with that for loop which will always give me "for n in range(2,2)". Would you recommend anything different? Or should I just skip the instructions and made my own solution?


#4

the code below is accepted

def is_prime(x):
flag = 0
if x < 2:
return False
elif x == 2 or x == 3:
return True
else:
for i in range(2,x-1):
if x % i == 0:
flag = 1
break
else:
flag = 0
if flag == 1:
return False
else:
return True


#5

good :slight_smile: you yourself sloved this.

however, you could do this

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

or here don't need else too .

but it's very good that you was continuously trying :slight_smile:


#6

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