Break and Continue in Loops:
break statement
When a break statement executes inside a
loop, control flow "breaks" out of the loop immediately:
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking
from loop")
break
i += 1
The loop conditional will not be evaluated after the break statement is executed. Note that break statements are
only allowed inside loops, syntactically. A break statement inside a function cannot be used to terminate loops
that
called that function.
Executing the following prints every digit until number 4 when the break statement is met and the
loop stops:
0
1
2
3
4
Breaking from loop
break statements can also be used inside for loops, the other looping construct provided by Python:
for i in (0, 1, 2, 3, 4):
print(i)
if i == 2:
break
Executing this loop now prints:
0
1
2
Note that 3
and 4 are not printed since the loop has ended.
If a loop has
an else
clause, it does not execute when the loop is terminated through a break
statement.
Example:
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
continue statement:
A continue statement will skip to the next iteration
of the loop bypassing the rest of the current block but
continuing the loop. As with break, continue can only appear inside loops:
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
0
1
3
5
Note that 2 and 4 aren't printed, this is because continue goes to the next iteration instead of continuing on
to
print(i) when i == 2 or i == 4.
Example:
Continue to the next
iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
OUTPUT:
1
2
4
5
Pass statement:
In Python programming, the pass statement is a null statement. The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.However, nothing happens when the pass is executed. It results in no operation (NOP).
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.
Example: pass Statement
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Comments
Post a Comment