break while an iteration and after an iteration
Question:
In my 2 scripts it looks as the break
statement can break out of the loop both: while the iteration process is running, and also after an iteration ends.
But I thought that break
can merely break the loop while the iteration, and not after it.
I find it meaningful because the outputs vary depending on how the break
functions with iterations.
list = [1,2,3,4,5]
for i in range(len(list)):
if i ==1:
break
print("loop is broken")
output:
loop is broken
In the above example, according to the outcome, the break
only breaks out of the loop after the first iteration ends.
list = [1, 2, 3, 4, 5]
for i in list:
if i == 1:
print("loop is broken")
break
print("string is not printed")
Output:
loop is broken
Now it contradicts the assumption that the break
breaks only once the iterator finishes, otherwise string is not printed
would have been printed.
Answers:
In your first code snippet, you use for i in range(len(list)):
meaning that i
will only equal 1
on the second iteration, so ‘loop is broken’ gets printed.
In the second code snippet, you use for i in list:
, so i
equals 1
on the first iteration, so only ‘loop is broken’ has a chance to get printed before the break.
In my 2 scripts it looks as the break
statement can break out of the loop both: while the iteration process is running, and also after an iteration ends.
But I thought that break
can merely break the loop while the iteration, and not after it.
I find it meaningful because the outputs vary depending on how the break
functions with iterations.
list = [1,2,3,4,5]
for i in range(len(list)):
if i ==1:
break
print("loop is broken")
output:
loop is broken
In the above example, according to the outcome, the break
only breaks out of the loop after the first iteration ends.
list = [1, 2, 3, 4, 5]
for i in list:
if i == 1:
print("loop is broken")
break
print("string is not printed")
Output:
loop is broken
Now it contradicts the assumption that the break
breaks only once the iterator finishes, otherwise string is not printed
would have been printed.
In your first code snippet, you use for i in range(len(list)):
meaning that i
will only equal 1
on the second iteration, so ‘loop is broken’ gets printed.
In the second code snippet, you use for i in list:
, so i
equals 1
on the first iteration, so only ‘loop is broken’ has a chance to get printed before the break.