# 6. is_prime with while

#1

why do i get this error. Can somebody help? I've checked other related topics but nobody seems to tried it with while.

P.S. I've run it with and without break as well.

``````def is_prime(x):
y=1
while y<x:
if x%y==0:
return False
else:
return True
break
y+=1
else:
return False``````

#2

Just quickly, still studying, indent another level `y+=1`.

Now let's consider anything after `return`. Will it ever be reached?

And now we need to look at the core logic of this program. If I were an examiner, which would never happen, but just say... I would toss this paper. Purely on the basis of the first line inside the function.

Unity is not prime because any definition of it would be circular reference. Nobody would state a variable with that value to start a loop in search of primes.

Consider also, the abstract logic: Just because it is not false does that mean it is true? Screwy, I know. If a condition can be evaluated explicitly then it can return whatever. Those opposed to this ought not be seen as opposites, as much as non-candidates.

Along this line of thinking we get to the `else:` in the context of `if` in a `while` statement. THe whole construct is unnecessary. All that needs be is the step on y, which of course would not be 1.

The final outcome will be `True` if the while loop completes, otherwise, `False`.Scratch some code along these lines and keep us posted!

#3

If you use the `while else`
and Python has an `indentation` dependency
you can not use an expression before the ELSE ....
The ELSE will only be executed if the condition of the WHILE runs into a `False`

``````n = 1
while n < 3:
print n
n = n + 1
else:
print "Done"``````

[output]

``````1
2
Done``````

A return statement and the break statement will EXIT the `while else`-loop
without executing the ELSE code-block.

For a definition of a `is_prime` function
have a read through the == discussion / opinons ==
http://stackoverflow.com/questions/14656473/python-beginners-loop-finding-primes

#4

... introduces a block `:` which in the `return` I refer to is `True`, when corresponding with `while`.
.

#5

Hi everyone,

thanks for the feedbacks. At last, I've decided to let go of "while" and used "for" instead.

This is how it looks now and it works.

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

#6

This will return `False` for `2`.

#7

hi,

i prevented it with these lines:

if x<2:
return False