Reputation: 105
I had assumed my Python prime number list was good. But it's printing out numbers the moment it sees that it is not divisible by 2. I've tried to iterate loops through the list that contains other prime numbers such as 3, 5, 7 ... but it does not seem to work still.
primes = []
input = raw_input("> ")
input2 = raw_input("> ")
for num in range(int(input), int(input2)):
for j in primes:
if not primes:
break
else:
if j % num ==0:
break
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
break
print primes
This prints out numbers divisible by 3 but not divisible by 2.
for num in range(int(input), int(input2)):
if not primes:
break
else:
for j in primes:
if j % num ==0:
break
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
break
print primes
This code is printing out an empty list. It made sense to me logically but the code is not executing the way I expect it to. What is wrong here???
Upvotes: 1
Views: 116
Reputation: 1727
Your first for loop isnt doing anything useful:
for num in range(int(input), int(input2)):
for j in primes: #there is nothing in list 'primes'
if not primes: #this won't execute
break #this won't execute
else: #this will execute
if j % num ==0: #this will execute
break #break if statement, repeat for loop
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
break
print primes
With that said, this would be the most convenient way to get your desired output:
primes=[]
input = raw_input("> ")
input2 = raw_input("> ")
for num in range(int(input), int(input2)):
if all(num%i!=0 for i in range(2,num)):
primes.append(num)
print primes
Upvotes: 3
Reputation: 140
your second "else" seems to be in the wrong place. try this modified version of your program :
primes = []
input = raw_input("> ")
input2 = raw_input("> ")
for num in range(int(input), int(input2)+1):
# prime numbers are greater than 1
if num > 1 :
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
print primes
Upvotes: 1