Tests to perform Else behavior
I performed the following tests, I thought the for
with else
could be affected by if
, by internal variables and by break
, to test I ran the following tests.
Test 1
Code
for i in range(2, 10):
print("Dentro" , i)
else:
print("Fora" , i)
Upshot
Dentro 2
Dentro 3
Dentro 4
Dentro 5
Dentro 6
Dentro 7
Dentro 8
Dentro 9
Fora 9
Executed at the last index
Test 2
- unconditional
- break-hearted
Code
for i in range(2, 10):
print("Dentro" , i)
break
else:
print("Fora" , i)
Upshot
Dentro 2
Lse is not executed
Test 3
- paroled
- break-free
- external variable
Code
variavel_externa = 1
for i in range(2, 10):
print("Dentro" , i)
if(variavel_externa == 1):
print('achou')
else:
print("Fora" , i)
Upshot
Dentro 2
achou
Dentro 3
achou
Dentro 4
achou
Dentro 5
achou
Dentro 6
achou
Dentro 7
achou
Dentro 8
achou
Dentro 9
achou
Fora 9
Executed at the last index
Test 4
- paroled
- break-hearted
- external variable
Code
variavel_externa = 1
for i in range(2, 10):
print("Dentro" , i)
if(variavel_externa == 1):
print('achou')
break
else:
print("Fora" , i)
Upshot
Dentro 2
achou
Lse is not executed
Test 5
- paroled
- break-free
- internal variable
Code
for i in range(2, 10):
print("Dentro" , i)
if(i == 2):
print('achou')
else:
print("Fora" , i)
Upshot
Dentro 2
achou
Dentro 3
Dentro 4
Dentro 5
Dentro 6
Dentro 7
Dentro 8
Dentro 9
Fora 9
Executed at the last index
Test 6
- paroled
- break-hearted
- internal variable
Code
for i in range(2, 10):
print("Dentro" , i)
if(i == 2):
print('achou')
break
else:
print("Fora" , i)
Upshot
Dentro 2
achou
Lse is not executed
Test with the question code
- paroled
- break-hearted
- internal variable
Code
for i in range(2, 10):
for j in range(2, i):
if i % j == 0 and i != j:
print('break', i)
break
else:
print(i)
Upshot
2
3
break 4
5
break 6
7
break 8
break 9
Else is not executed when the break is not executed
Completion
It just doesn’t run Else when "break" runs.
In the books I read, I do not study anything just for a hobby, they did not comment on ELSE together with FOR, but this way generates the expected result. So this structure can be used is "pythonica"?
– hugo-souza
Yes, in a way, because you will be using the structure for exactly what it proposes to do.
– Woss