I tried to make a program that shows all prime number till the limit
but the code shows each factor adding to the ans
list.
How do I fix this?
limit = 34
num = [value for value in range(2, limit 1)]
factor = 2
ans = []
while True:
if factor not in num:
factor = 1
elif factor in num:
ans.append(factor)
for ele in num:
if ele % factor == 0:
num.remove(ele)
print(ans)
Expected Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
CodePudding user response:
You need to ensure the factor
variable is bounded.
limit = 34
num = list(range(2, limit 1))
factor = 2
ans = []
while factor <= limit 1:
if factor not in num:
factor = 1
elif factor in num:
ans.append(factor)
for ele in num:
if ele % factor == 0:
num.remove(ele)
print(ans)