Is_Prime returns noe


#1



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

It returns non for is_prime(2), and I don't see the error.


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


#2

In your for loop,
when n=2 then loop won't start because it's mean start from 2 to 1, not possible.

You may try this :
def is_prime(x):
if x>1:
flag=0
for i in range(2,x-1):
if(x%i==0):
flag=1
break
else:
flag=1

if flag==1:
    return False
else:
    return True

print is_prime(4)


#3

This problem is actually more complicated than it seems, as not only do you need to first run it through the if condition x<2 but after that run it through 'if x==2, return True'

finally, you also need to take into account the fact that the exercise is only going to evaluate the first boolean it gets that's run through the iteration. Therefore, you need to also append the values as strings to a new list and finally return the result of the last value in the list being equivalent to the phrase of your choosing, preferably "True". Here's the whole code...try and understand how it works before going ahead and hitting 'save and submit code'. This code will work.

def is_prime(x):
    lst = []
    if x<2:
        return False
    elif x==2:
        return True
    else:
        for i in range(2, x):
            if x%i!=0:
                lst.append('True')
            else:
                lst.append('False')
                break
    result = lst[(len(lst)-1)]
    if result == "False":
        return False
    else:
        return True
            

is_prime(9)

All the best !


#4

Indentation problem. The else should line up with for, not if so the loop completes first.


#5

Thanks, but I don't understand this [edit] Prime problem!


#6

Well, if you don't understand what a prime number is, i recommend a wikipedia page (prime numbers), if you have a question about the exercise in particular, create your own topic so we can help you


#7

A post was split to a new topic: Is prime