0

I am new to python programming. I am a little confused in the below code, how else statements work without corresponding if statement. Could anyone please explain to me the below code. Program is Prime number between two intervel.

start=int(input("Enter Number: "))
    stop=int(input("Enter Second Number: "))
    
    for i in range(start,stop):
        if i>1:
            for j in range(2,i//2+1):
                if(i%j==0):
                    break
            
    
            else:
                print(i)
senpaswan
  • 13
  • 1

1 Answers1

0

In Python, loops can have an else statement. However, think more of a try-except statement than a if clause.

An example:

for item in container:
    if search_something(item):
        # Found it!
        break
else:
    # Didn't find anything..
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
  • 1
    `for-else` has nothing to do with the emptiness of what you are iterating over. The `else` triggers if the `break` is never reached. – user2390182 Dec 20 '20 at 11:18
  • Sorry for the unclear answer. But for-else is the answer to the question I think (namely why there is a else without an if). – Michael Dorner Dec 20 '20 at 11:22
  • Yup, of course, hence the duplicate question. But any answer should mention the all important relation between the `break` and the `else`. – user2390182 Dec 20 '20 at 11:26