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) `
The problem in your code is that once
primeis set toFalseit will never ever again get to beTrue.The fix is simple: set it to
Trueat the start of every iteration:Note that it is not necessary to add parentheses around the
ifcondition. Also, it is not necessary to doprime==Truewhenprimeis known to be a boolean. Just test that boolean.The
i > 1is a bit overkill. It would be better to start the iteration at at least 2 and then never worry about it again:And yes, it is a nice feature of Python that a
forloop can have anelseclause. It kicks in when the loop finishes normally, without break. In this case it means we can drop the boolean nameprime.We get: