Why does else leave it outside when printing 50-100 primes with python?

import math
for i in range (50100room1):

for t in range(2,int(math.sqrt(i))+1):
    if i % t == 0:
        break
    else:
        print(i)
       

if I write like this, what I print out is 51, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53.

import math
for i in range (50100room1):

for t in range(2,int(math.sqrt(i))+1):
    if i % t == 0:
        break
else:
        print(i)

when I took out the else, the result was correct. But I don"t think it"s logical, huh? Shouldn"t it be printed in the for loop? If you take it out, is it still in the for loop?

Mar.07,2021

the syntax of Python for, after the loop condition is executed, it will go into the else branch to execute.

for i in range(3):
    print(i)
else:
    print(i)

result:
0
1
2
2


when iRight 51, the inner loop:
twee2, not divisible, you print (i)
twee3, can be divisible, you break
.
actually, 51 is not a prime, you only judge once that it is not divisible by 2, then print. The right thing to do is: 2-8 can not be divisible before print.


ok, Let's talk about two points:
1. There is something wrong with your algorithm logic.

for t in range(2,int(math.sqrt(i))+1):
    if i % t == 0:
        break
    else:
        print(i)

the purpose of your code is to determine whether there are divisors other than 1 and itself. But once I is not divisible by t, you print, this is wrong, it should be the end of the whole for cycle and there is no other divisor to print, for example, 99 is not divisible by 2, and you print it, which is obviously wrong. So the right thing to do is to judge whether the loop is complete. How to tell, one way is to compare the count to int (math.sqrt (i)) + 1) or mark the abnormal end, but python has a better way. This brings us to the second point.
2, for. Else syntax, which executes the else statement when the for ends normally. That's why you took the else to the outside floor and got the right result.

Menu