Prime -- for loops and if statements question


#1



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


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


I know this has been covered by other answers but I don't understand why mine can't work as well. An if statement can't go under a for loop here -- but don't we use conditionals in loops all the time? Why doesn't it work in this case even if return True exists outside the loop?


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


#2

Your is_prime() function will fail on 0,1 and all negative numbers.
suppose at 0..
is_prime(0)
When it starts looping then it will see range(2, -1).. which is an empty list,thus your loop will not able to go inside for loop and return False instead it will runelse statement and return True

solution..

instead of putting x <= 1 (if statement inside of for loop) , create if (initial of your function)statement that checks if x is less than or equal to 1 ,if it is then return False


#3

Thank you greentreemee! Your answer makes total sense. Why then is the language of the instructions "02.For each number n from 2 to x - 1, test if x is evenly divisible by n." ? Just curious as to what they mean and what I'm missing.


#4

For each number n from 2 to x - 1, test if x is evenly divisible by n.

It was just logic to test prime-property of a number.
Although it does not mention what'd be the number x.
It can be 0 or 1 or any number.
Tho at beginning of program It did mention that CC editor will only check for positive integer. (so eliminates the negative number from scene ) thus this code works for positive numbers.

Ps: delete your final working code(by editing) so other will not able to copy-paste and use it(cheat).
:slight_smile:


#5

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