Programme to print all the Prime numbers within a range

51 Views Asked by At

So basically the aim of the programme is to print the prime numbers between two numbers.I did find the solution to the problem in the internet but i cannot understand what was worng with my code,I come from a C programming background and now i am learning python, apparently the other solutions use a 'for-else' thing but can u please spot the logical error or whatever error here?(I am an Undergrad 1st Year student so pls have mercy on me).

`

 n1=int(input("Enter the lower limit of the range: "))

 n2=int(input("Enter the upper limit of the range: "))

 prime=True

 for i in range(n1,n2+1):

 if(i>1):
     for j in range(2,i):
         if(i%j==0):
             prime=False
             break
     if(prime==True):
         print(i)       `
1

There are 1 best solutions below

0
trincot On

The problem in your code is that once prime is set to False it will never ever again get to be True.

The fix is simple: set it to True at the start of every iteration:

for i in range(n1, n2 + 1):
    prime = True
    if i > 1:
        for j in range(2, i):
            if i % j == 0:
                prime = False
                break
    if prime:
        print(i)

Note that it is not necessary to add parentheses around the if condition. Also, it is not necessary to do prime==True when prime is known to be a boolean. Just test that boolean.

The i > 1 is a bit overkill. It would be better to start the iteration at at least 2 and then never worry about it again:

for i in range(max(n1, 2), n2 + 1):

And yes, it is a nice feature of Python that a for loop can have an else clause. It kicks in when the loop finishes normally, without break. In this case it means we can drop the boolean name prime.

We get:

for i in range(max(2, n1), n2 + 1):
    for j in range(2, i):
        if i % j == 0:
            break
    else:
        print(i)