You need to set your k
flag back to 1
each time the for i
loop moves to the next number:
for i in range (2,10):
k = 1
for j in range (2,i):
if ((i%j)==0):
k=0
if (k==1):
sum+=i
Without doing that your code only ever finds 5
to be a prime number, and ignores anything after that.
Note that in Python, 0 is considered false when used in a boolean context (such as an if
statement), 1 is true, so you can just use if k:
. Better still, use True
and False
and better variable names, such as is_prime
rather than k
. You can drop a lot of those parentheses:
sum = 0
for num in range (2, 10):
is_prime = True
for i in range (2, int(num ** 0.5) + 1):
if not num % i:
is_prime = False
if is_prime:
sum += num
I also made use of the fact that you only need to check up to the square root of a number to see if there are divisors, cutting your loops down significantly.
Last but not least, you can make use of the for ... else
construct; if you use break
in a for
loop, the else
branch never gets executed, but if the for
loop completes to the end without breaking out, it is; this removes the need for a boolean flag:
sum = 0
for num in range (2, 10):
for i in range (2, int(num ** 0.5) + 1):
if not num % i:
break
else:
sum += num