0

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
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Radhu
  • 21
  • 1
  • 1
  • 1
    Do you understand what does `else` do when it's below `for`, and `if`? – Remi Guan Feb 11 '16 at 06:38
  • While your direct question has already been answered by Kevin and Nander, an arguably more Pythonic solution uses list comprehension for the inner loop: `if num > 1 and all(num % i != 0 for i in range(2, num)): print(num)`. You could also replace the upper bound with `range(2, int(num**0.5) + 1)` to save some iterations (see [here](http://stackoverflow.com/a/5811176/92092)). And finally, you should avoid using [built-in function names](https://docs.python.org/3/library/functions.html) `max` and `min` as variable names because you hide those functions when doing so.. – stephan Feb 11 '16 at 07:40

3 Answers3

1

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:

  • For each number, do a modulo calculation and break if it leads to 0
  • If none of the calculations lead to 0, you find a prime (and thus print it)

En your second example:

  • For each number, do a modulo calculation and break if it leads to 0
  • If it doesn't lead to 0: print the number. Which happens quite more often than the else in example 1.
Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
0

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

0

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)
Obsidian
  • 515
  • 3
  • 10