Control Statements
There are three control statements that can be used with for
and while
loops to alter their behavior.
They are pass, continue, and break.
1. pass:
Whenever loops, functions, if statements, classes, etc., are created, it is necessary to write a block of code in them. An empty code inside a loop, if statement, or function will give an error.
Example:
i = 1
while (i < 5):
Output:
IndentationError: expected an indented block
To avoid such an error and to continue the code execution, the pass
statement is used. The pass
statement acts as a placeholder for future code.
Example:
i = 1
while (i < 5):
pass
for j in range(5):
pass
if (i == 2):
pass
The above code does not give an error.
2. continue:
This keyword is used in loops to end the current iteration and continue to the next iteration of the loop. Sometimes within a loop, we might need to skip a specific iteration. This can be done using the continue
keyword.
Example 1:
for i in range(1, 10):
if(i % 2 == 0):
continue
print(i)
Output:
1
3
5
7
9
Example 2:
i = 1
while (i <= 10):
i = i + 1
if (i % 2 != 0):
continue
print(i)
Output:
2
4
6
8
10
3. break:
The break
keyword is used to bring the interpreter out of the loop and into the main body of the program. Whenever the break
keyword is used, the loop is terminated, and the interpreter starts executing the next series of statements within the main program.
Example 1:
i = 1
while (i <= 10):
i = i + 1
if (i == 5):
break
print(i)
Output:
2
3
4
Example 2:
for i in range(1, 10):
print(i)
if (i == 5):
break
Output:
1
2
3
4
5