is_Prime


#1



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


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

When I click on "save and submit", it runs forever and won't show the result.

I wanted to code the following logic.
- while input, x, is greater than 1, if any number ranging from 2 to x-1 can divide x evenly, it is not a prime number. Hence, False.
- in all other cases, i.e., if x ==1 or x cannot be divided evenly by 2 to x-1, it should be a prime number.
What is wrong with my code?


Replace this line with your code.


#2

Best if you do not have an else branch in your if statement.


#3

You want a True return only when loop is ended. For example, if x = 9, your rutine compare 4%2 == 0, and it jumps to else: where it return True. But 9 is not a prime number. And you don't need to create a range (2, x-1), since, range don't include x.


#4

The range is not a problem, either way since the top half of the values are superfluous.

Where I see an issue is in the while loop where an if statement would suffice.


#5

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