6. is_prime


#1



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


Why is x = 9 returning true?


def is_prime(x):
    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:
                return False
                break
            else: 
                return True

is_prime(9)


#2

Delete the else statement in

and then delete the indents of return True so it is lined with the for loop. It should look like this in the end:

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

#3

Probably a stupid question but could someone help in explaining why its x-1? Like since the second argument of range is anyway one number lower, why don't we use x only?


#4

The argument in the coding is looking for any number that divides evenly into variable x. However, with prime numbers, 1 and x will still divide into x - for example, if we take 23, it's still divided by 1 and 23.

If you use 'x' and not 'x - 1', the program will try 23 / 23 and say it's not a prime number.


#5

The code does work if you use range(2,x). I believe you are correct. For example, if x = 23, Python will only check numbers 2 to 22 if you use range(2,x).


#6

I don't understand why you delete the else statement and delete the indents of the return True so it is lined with the for loop.


#7

Hey bud, the following code worked:

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

Keep a close look on the indentation. E.g. I indented the last ELSE one more tab and it didn't loop so it got stuck at number 9 (saying its a Prime, but we all know 9 is not a prime). So delete 4 spaces or one tab of your last ELSE and try it again. Keep in mind I used range 2, x and not 2, x-1, as the range of (1, 4) is actually 1 2 3. Does that make sense to you?


#8

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