Is_prime


#1



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


I've set up my code to see what is going on in the background here and it's all sorts of messed up.
I'm wondering why my code printing out all of the conditions:

True
False
True
True..

I feel as if something is broken with the iteration which is causing this to fail but I could use a little push in the right direction.


def is_prime(x):
    if x == 2:
        print "True"
    elif x > 1:
        for i in range(2, x):
            if x % i == 0:
                print "False"
                print "Not Prime"
            else:
                print "True"
    else:
        print "False"


is_prime(9)


#2

This function is not condusive to printing. Use return.

True    # i is 2
False   # i is 3
True    # i is 4
...

Let the caller print this. Your function should return only a boolean and print nothing.


#3

This code is being used just for my test environment. When I 'return' the function it fails at is_prime(9) which is why I've moved it into a more bug testing 'printing' environment.


#4

I think I found the problem here. I'm missing a break statement! Confirm?


#6

If the concern is printing, then yes, a break statement is paramount. The outcome has been reported with certainty... Number is divisible. Not a prime.

The else after it is a deal breaker, though. It gives false positives.

We do not even need an else to this conditional. The if covers it. Let the loop center around that.


#7

I did notice that you had given others the same advice so I took the else statement out. Being new to programming I think that we newbies believe every IF must have an ELSE. When I took it out however the same problems were still present. When I added the break statement following my return True.. it allowed me to move forward. I'm going to throw it into my test environment again because simply moving forward doesn't serve me if I don't actually understand the concepts.


#8

def is_prime(x):
    if x == 2:
        print "True"
    elif x > 1:
        for i in range(2, x):
            if x % i == 0:
                print "False"
                print "Not Prime"
            else:
                print "True"
    else:
        print "False"

Reworking your code gives the result you are expecting...

def is_prime(x):
    if x == 2:
        print True
    elif x > 2:
        for i in range(2, x):
            if x % i == 0:
                print False
                print "Not Prime"
                break
        else:
            print True
    else:
        print 'Invalid input'

is_prime(9)
# False
# Not Prime
is_prime(1089)
# False
# Not Prime
is_prime(2)
# True
is_prime(17)
# True
is_prime(1)
# Invalid input

Note the inner else is on the for, not the if. The outer else is on the outer if.


#10

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