Reputation: 461
So I'm trying to print all the prime numbers up to 100. Here's my code so far:
primes = []
for num in range(100):
if num > 1:
for i in range(2, num):
if num % i != 0:
primes += [num]
break
else:
break
print(primes)
However when i run the code, it only does the calculation (if num % i != 0
) for the first iteration in the range (for i in range(2, num)
). This is a problem in the case of numbers like 15, where the first iteration in for i in range
is 2. 15 divided by 2 does not give a whole number, and so it runs primes += [num]
. It has taken the first iteration and has not run the rest of them. Is there a way to run all the iterations in the range?
Upvotes: 1
Views: 81
Reputation: 9494
Try this:
primes = []
for num in range(100):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
print(primes)
The code will execute the else
block only if the inner for
loop is exhausted, i.e completes it's all iteration without breaking.
Upvotes: 1
Reputation: 1635
You got the logic somewhat wrong. Here's how you've to do it
primes = []
for num in range(2, 100): # 0 and 1 aren't primes
for i in range(2, num):
if num % i == 0:
break
else: # the else condition is for the for loop i.e. if it executes without break
primes.append(num)
print(primes)
Upvotes: 1
Reputation: 539
tried to adapt to your approach although, I think there should be better ways to solve this problem
>>> primes = []
>>> for num in range(2,100):
... p = True
... for i in range(2, num):
... if num % i == 0:
... p = False
... if p:
... primes += [num]
...
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Upvotes: 0
Reputation: 2658
Here is my take on it.
>>> def primes(limit=100):
... for number in range(limit):
... is_prime = all([number % divisor != 0 for divisor in range(2, number)])
... if is_prime:
... yield number
...
>>> list(primes(10))
[0, 1, 2, 3, 5, 7]
>>> list(primes(100))
[0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>>
Is not complete, 0 and 1 are not primes. But I think you get the idea.
Upvotes: 0