The statement break
serves to interrupt the execution of a repeat loop (while
and for
), no more code below it being executed that is within the repeat structure.
See below for an example:
for numero in range(5):
if numero > 2:
break
print(numero)
See online: https://repl.it/repls/FruitfulDigitalPatterns
In the above code, only the numbers 0, 1 and 2 will be printed because the break
interrupts the replay without caring about the rest of the code. That’s exactly why Python doesn’t allow you to write code below and in the same block as it, since that wouldn’t make any sense.
This statement is also very similar to statement continue
, which is another instruction in which it ignores the code below it, but continues the execution of the repeating structure.
for n in range(1000):
if n > 10:
break # Sai do for loop
if n % 2 == 0:
continue # Volta para o início do for loop
print(n)
See online: https://repl.it/repls/TediousTriflingAddons
Both the break
as to the continue
are present in many programming languages such as Python, Java, Javascript, Ruby, etc., having the same function within repetition structures.
But then break wouldn’t skip pos += 1 in my code?
– Crow404
Would not, the statement
break
pula that line of code and everything below it that is in the same repeat block when running inside your blockif
.– JeanExtreme002