6. is_prime


#1

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


it tells me that is_prime(2) returns none instead of False. That means it's not iterating through my loops properly but not sure why.


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


#2

well, for x=2 we get the following loop condition:

for n in range(2, 2 - 1)

2 < 2 -1 is false, so the loop never runs


#3

Thanks heaps, I was running through it and I saw another post you commented on and the problem seemed similar so I wokred through it and I've come up with a solution of
def is_prime(x):

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


#4

do you understand the solution?


#5

Yeah I do, it works becasue before the code wouldnt iterate through every number in the range, it would go unitl it proved false and move onto the else. By eliminating the else it will keep iterating over until one of them works and if one doesnt work it will ende the loop beacuse its out of numbers and once the loop is ended it will return true. Confirming the number is infact prime.


#6

Very good, you can now move on to the next challenge :slight_smile:


#7

I still don't gettit


#8

this is not your topic? If you need help, please make a new topic


#9