This code take the values of lista
and goes putting in ordenado
. In the first iteration of for
ordenado
is empty then, the instruction jumps to the else
and add value 11 in ordenado
. In the second iteration the instruction already enters the second for
and compares if numero < valor
, and only compares with 11 because this is the only ordered element so far, then the other 11 is added to ordenado
in block else
. In the third iteration occurs the same as the second and 15 is added to the ordenado
. In the fourth iteration numero = 12
, the second for
compare if numero < valor
numero=12
with (11,11,15), when it comes to the comparison 12 < 15
the instruction enters the if
and inserts the 12 into the second position, previously occupied by the 15 that will now occupy the 3rd. In the 4th iteration, note that numero
= 12 and this was exchanged with the 15 no if
, that means that ordenado = [11,11,12,15]
, poi the 15 was pushed to the next position, the list ordenado
which had 3 values (11,11,15) now has 4, so if you do not find a break there will be a new comparison 12 < 15
, then another change occurs, now we have another 12 in the 4th position and the 15 is pushed again to the 5th. Again ordenado
increased one more element so the previous Oxyclo repeats endlessly.
1 - Prevents the change to be repeated for the same value 12 and 15 example as said before.
2 - The else
this ident with the second is so that it runs every time, it is where list values are added to ordenado
and the break prevents the loop , repeating the one before, if it was idented with the if or the number was changed or was added at the end list, this would prevent all of the lista
were added to ordenado
.
3 - Why it needs to be executed every time, in this example, 15 times to add all values of lista
in ordenado
4 - In that case Else would be out of the loop so it runs only once and at the end of the execution.
To help with a point, in Python a
for
may have aelse
associated with it. Basically, if the loop is not interrupted by abreak
, he enters theelse
, see the documentation– hkotsubo