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

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.


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


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.


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.


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