Is_Prime


#1



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


Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.


I do not understand why it is not working for x=9.Please help.


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


#2

the first value tested by the loop for x=9, is 2, agree? so then we get:

if 9%2==0:

which is false. So, else will run. Which means a return keyword is reached

the moment a return keyword is reached, a function ends. This means, the loop has to break

Is this the desired behavior of your program?


#3

Thank you for the reply. How should I correct my code?


#4

i actually left that for you to figure out, based on my explanation, what is the problem and how do you think you can solve it? Please tell me, so i can fill in any missing gaps


#5
  1. The for loop should check remainder function for every number 2,3,4,5.....x-1.
  2. For the first encounter where input%x==0, the function should return False. This would mean there is one more number other than 1 and the input number itself, by which the input number is evenly divisible. Hence the input number is not prime.
  3. By checking x%item==0 inside a for loop, I assumed it will check for every value between 'Range(2,x).

This is how I would solve the problem.


#6

but as i just try to explain, this doesn't happen?

Your loop finishes in its first iteration because a return keyword is reached. Which causes the function to end. (in order for the function end, the loop needs to break)

So what would be the solution to prevent return True from being reached to early?


#7

Hi Stetim94,

The solution to prevent return True being reached so early is to place the return statement outside the loop.

Or

I can use a counter (initially set to 0) wherein the counter gets incremented to 1 each time a number in range(2,x) is a divisor of the input number. So at the end if counter>0, input number is not prime.


#8

this sounds like the good solution :slight_smile: try to implement it. That should solve the problem :slight_smile:


#9

Hi Stetim94,

Thank you helping me figure this out :grin:


#10