Reputation: 25
I am trying to find every prime number in a user chosen range, list them and count them. my code counts and list number that are not prime. I really can't find why? Could somebody please help me.
print("This code will count how many prime number exist in a certain range")
count = 0
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
prime = []
for num in range(lower, upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
break
print(prime)
print("There are", len(prime), "prime number between", lower, "and", upper)
Upvotes: 2
Views: 182
Reputation: 1
Here is a solution to get the prime number form a list. Ask user for range between the prime number should be created and store it in list
:
list4=list(range(3,10,1))
prime_num=[x for x in list4 if x%2!=0 and x%3!=0]
Upvotes: 0
Reputation: 12107
Your problem is that you dont wait all division checks to append the number to primes list:
if (num % i) == 0:
break
else:
prime.append(num)
break
The fix for your code:
is_prime =True
for i in range(2,num):
if num % i == 0:
is_prime = False
break
if is_prime:
prime.append(num)
$ python prime_test.py
This code will count how many prime number exist in a certain range
Enter lower range: 12
Enter upper range: 20
[13, 17, 19]
('There are', 3, 'prime number between', 12, 'and', 20)
Upvotes: 1
Reputation: 1469
The problem is here,
for i in range(2,num):
if (num % i) == 0: #If num is divisible by SOME i, it is not prime. Correct.
break
else: #If num is not divisible by SOME i, it is not prime. WRONG.
prime.append(num)
break
You should have checked the condition like this : If num is not divisible by ANY i, it is prime
.
With minimum changes using else with for,
for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
Read more : Why does python use 'else' after for and while loops?
Upvotes: 1
Reputation: 7100
Your primes part is wrong. I'm going to abstract that to a different method to make it easier. To be prime, a n%x
must hold up for any x
such that x
is in the set of numbers [2,ceil(sqrt(n))]
.
Make sure you import math
def is_prime(num):
for i in range(2, math.ceil(num**(1/2))):
if num%i==0:
return False
return True
Then, just replace
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
break
With,
if num>1:
if is_prime(num):
prime.append(num)
Upvotes: 1