Reputation: 21
I'm pretty new at coding so sorry if this is a silly queastion. I've got a problem with this for loop at Python:
for n in (2, (k / 2)):
if k % n == 0:
print ("Yes")
else:
print ("No")
The problem is that I get two prints, sometimes contradictory ones like Yes
and No
for 3, 25, 35 and other numbers.
My purpose is to detect prime numbers.
I use PyCharm btw.
Thank you.
Upvotes: 1
Views: 314
Reputation: 20414
The syntax for n in (a, b)
does not cycle n
between the values a, a+1, a+2, ..., b
, it literally makes n
take the values a
and then b
as the syntax (a, b)
defines a tuple which you iterate over.
You are almost definitely looking for the range()
function which returns an iterable which you can iterate over in the for-loop so that n
takes the range of values from a
to b
(not including b
).
So:
for n in range(2, int(k / 2)):
note that we must also convert the result to an integer with int()
since range doesn't accept floats (decimals)
As for making the prime test work, you don't want to cycle all the way up to half the number, you only need to go up to the square root of the number. Also, whenever you find a divisor, you can print('no')
and break
out of the loop, but when a number doesn't divide the prime candidate, you can't print('yes')
as there may be divisors that you haven't checked yet. So we can only print('yes')
if we complete the for-loop
without breaking out of it early. This is most easily achieved with a function:
def is_prime(k):
if k <= 1:
return False
for n in range(2, int(k ** 0.5) + 1):
if k % n == 0:
return False
return True
and then we can see it works:
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
>>> is_prime(6)
False
>>> is_prime(7)
True
>>> is_prime(8)
False
>>> is_prime(9)
False
>>> is_prime(10)
False
>>> is_prime(11)
True
Upvotes: 4
Reputation: 409136
(2, (k / 2))
is a tuple of two values, it's not a range. That means the loop will always iterate two times, one with the value 2
and one with the value k / 2
.
You need to create an instance of the range
class:
for n in range(2, int(k / 2)):
...
That range
object will create an object that can be iterated over, with the values from 2
to (k / 2) - 1
.
Upvotes: 2