Indentation in statement else

1

Hello, I would like a clarification on the difference in the indentation of the else, "out" of the if. In case it is to return the primus numbers to the nth value 'n'.

First case:

for i in range(2, n):
    for j in range(2, i):
        if i % j == 0 and i != j:
            break
    else:
        print(i)

Second case:

for i in range(2, n//2):
    for j in range(2, i):
        if i % j == 0 and i != j:
            break
        else:
            print(i)

grateful.

    
asked by anonymous 05.03.2018 / 21:44

2 answers

0

In fact, the indentation serves to define which structure else belongs. In the first case, else belongs to the for loop (yes, that exists in Python), while in the second else would belong to if .

for i in range(2, n):
    for j in range(2, i):
        if i % j == 0 and i != j:
            break
    else:
        print(i)

In this case, the value of i will vary from 2 to n-1 and the value of j will vary from 2 to i-1 . If a value of j is found that is a divisor of i , the j loop is broken. The else block will be executed whenever the loop terminates without interruption, that is, if the value of j reaches i-1 , which is its upper limit, without one of its values being i . If break occurs, the else block will not run. It is worth mentioning that the i != j condition here is unnecessary since j will not reach i since its upper limit is i-1 .

As for the second case:

for i in range(2, n//2):
    for j in range(2, i):
        if i % j == 0 and i != j:
            break
        else:
            print(i)

The else block will be executed at each loop in j where the j value is not a i splitter, which is likely to generate a result far beyond what is expected.

    
06.03.2018 / 00:43
1

The first one is not of if is for . If for is not executed then it drops to else . So in this case if the i is less than 2 else will be executed, which does not seem to make sense.

    
06.03.2018 / 00:09