The break statement in Python
The execution of a loop can be interrupted using the break
instruction.
Let us have a list lst
:
lst = [1, 2, 3, 4, 5]
Let's output all elements from it up to the number 3
, at which the execution of the loop will be interrupted. To do this, under the block with the condition, we write the instruction break
:
for el in lst:
print(el) # 1, 2, 3 if el == 3:
break
The break
instruction can terminate any loops: for
, while
.
Given a set:
tst = {1, 3, 6, 7, -9, 12}
Print its elements up to the first negative number.
Given a list:
tst = [7, 1, 2, 5, 0, 3, 9]
Find the sum of the elements of this list up to the first zero.
Given a number:
tst = 897654
Form a list from it up to the number 6
.