6/15, is_prime [SOLVED]


#1

my code lines are below:

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

it worked, but with some value of x such as 9, 27, 15

it returns the True instead of False

Could you please help me ?


#2

wel, if you add a simple print statement:

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

You will see that your for loop only execute once. Why? Well, in the first run of the loop, either if is true. If it is, False gets returned, the function ends (functions end when a return keyword is reached). If if is false, else gets executed. Return True, and the function (which includes the loop) ends. You might want to rethink how you indent your else statement. Or don't use an else statement at all


#3

Building off of that idea, think about when you want to break the loop. Also, you may want to consider storing the result of the boolean operation into a variable so that you can test it once the loop is over or broken.


#4

Isn't that the problem? The loop get broken to early, oops, you suggest to break it later, sorry, i read that wrong

Why? You can also simple return True when the loop is over and hasn't returned False


#5

when I try to run it (with the same code) on my own IDE, it works well.
but when run it on codecademy.
I received a warn like this:
Oops, try again.
Your function fails on is_prime(9). It returns True when it should return False.

sometimes it was 27, and sometimes it was 9.

I tried to use elif also. but nothing has changed


#6

Could you post your full code? That code will run, doesn't always mean it is correct. If your function is incorrect, it will still run, but might indicate 9 is a prime number (which is obviously not)


#7

thanks you all ! I got it to work!


#8

You're welcome, posting full answers is not allowed. Please read the guide-lines, thank you for your understandig.

for next time, use one of the two following options to make your code/indent visible:

select your code and press ctrl + shift + c (or cmd + shift + c if you use a mac)

if this instructions are unclear, you can also insert 3 backticks before and after your code, like so:

```
<p>visible</p>
```

the backtick is located above the tab key on your keyboard

If you don't use the instructions, indent will not be visible (while that is crucial while coding in python)


#9

after a several times of trying and searching, I got why it didn't work finally.

just removing else and set the final return out of last "if" conditiion :smiley:

def is_prime(x):
    if x < 2:
        return False
    if x ==2 or x == 3:
        return True
    for i in range(2,x):
        if (x % i) == 0:
            return False
    return True

#10

thanks for your advices,

I added < `` `> before and after my code line, it just showed on my preview. When I press post, it was not effected.


#11

You can't have spaces between the backticks. Single backticks are used for inline highlighting, like so, i uses single backticks


#13

could you please explain why it worked?


#14

A function ends the moment a return statement is reached, so lets say we have 9, and want to now if it is a prime number, we will loop over the numbers 2 till 8 (8 included), if x (9) is dividable by i (range 2 till to 8) if the statement is true, return False, function ends. If for all instances of i (2 till 8), x is not dividable by i, return True, function ends.

You could just add a bunch of print statements to see this in action, and gain a better understanding


#15

Thank you very much for your kindly reply


#16

Couldn't you remove you're second if statement? I believe this line is inherently understood in the for statement as both 2 and 3 are included in that range.


#17

at the first times, it did not work and the error appeared, that's why I had to add it. :slightly_smiling:


#18

If you want to find how many numbers are primes between a threshold you can use this code:

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
        return True

number1 = int(raw_input("1st number: "))
number2 = int(raw_input("2nd number: "))
    
for i in range(number1,number2 + 1):
    if is_prime(i) == True:
        print str(i) + "," ,

#19

Good demonstration of what you can achieve what you learn in the lesson. But i give you 2 suggestions: validate the user actually inputs a number (never trust a user, one of the most important lessons in programming), and check that number 2 is higher then number 1, or even better, is 2 is lower then 1, swap the numbers


#20

Yeah of course I just made a simple version! Can you please run this one and give me your suggestions?? Thanks for your contribution!

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
        return True

while True:
    number1=raw_input("1st number: ")
    if number1.isdigit():
        if int(number1) >= 0:
            while True:
                number2=raw_input("2nd number: ")
                if number2.isdigit():
                    if int(number2) > int(number1):
                        for i in range(int(number1),int(number2) + 1):
                            if is_prime(i) == True:
                                 print (str(i) + ",") ,
                        break
                    
                    elif int(number2) < int(number1) and int(number2) >= 0:
                        temp = number2
                        number2 = number1
                        number1 = temp
                        for i in range(int(number1),int(number2) + 1):
                            if is_prime(i) == True:
                                print (str(i) + ",") ,
                        break
                    
                    elif int(number2) == int(number1):
                        print ("Insert a different number than 1st one")
                    
                else:
                    print ("Try again with 2nd number")
        break                
    else:
        print ("Try again")

#21

I know, which is why i made a few suggestions. This is a whole lot more code, give me a couple of minutes to understand it

Why doesn't python have a do while loop? Ideal for this situation