Reputation: 21
To print the prime numbers in range program:
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
The output for the above is:
Enter lower range: 3
Enter upper range: 10
3
5
7
But,When I tried with the below code, the output is varying.
min=int(input("enter the min num"))
max=int(input("Enter the max num"))
for i in range(min,max+1):
if i > 1:
for j in range(2,i):
if (i%j) == 0:
break
else:
print(i)
Output:
enter the min num: 3
Enter the max num: 10
3
5
5
5
7
7
7
7
7
9
Upvotes: 0
Views: 95
Reputation: 1526
You have an indentation difference:
for j in range(2,i):
if (i%j) == 0:
break
## This piece
else:
print(i)
## This piece
In your first example:
En your second example:
else
in example 1.Upvotes: 1
Reputation: 515
You;re printing the value after each check success. You should put in a flag to print it out after all the checks. Something like below
for i in range(min,max+1):
if i > 1:
prime = True
for j in range(2,i):
if (i%j) == 0:
prime = False
break
if prime:
print(i)
Upvotes: 0
Reputation: 83
The 2 dimension loop is whats wrong with this code , when i = 5 , you go for j (2,5) so you go through the loop three times, you should add a command to prevent a repetition
Upvotes: 0