
Python Iteration Statements
Python Iteration Statements
Iteration:
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many programming problems. Iteration and conditional execution form the basis for algorithm construction. Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well.
One form of iteration in Python is the while statement. Here is a simple program that counts down
from five.
Example:
iteration.py n = 5 while n > 0: print n n = n-1 print(“iterated trough 5 values”) |
Iteration statements can be controlled by the following keyword:
• break
• continue
• Pass
In Python, break and continue statements can alter the flow of a normal loop.
Break Statements
The break statement terminates the loop containing it. Control of the program flows to the statement
immediately after the body of the loop.
Syntax:
break;
Flow Chart For Break Statements
Example:
break_test.py for val in "string": if val == "i": break print(val) print("The end") |
Output
s t r The end |
Continue Statement:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
Loop does not terminate but continues on with the next iteration.
Syntax:
Continue;
Flow chart for Continue Statements
Example:
continue_test.py for val in "string": if val == "i": continue print(val) print("The end") |
Output
s t r n g The end |
Pass Statement:
In Python programming, pass is a null statement.
Syntax:
Pass;
Example:
pass_test.py sequence = {'p', 'a', 's', 's'} for val in sequence: pass |
Output
#no output pass is just a placeholder for functionality to be added later. So no output.
Note: pass is mostly used in defualt cases, where just for future handling a case is defined.