The for Loop

Control statements with repetition statements, AKA loops, repeat an action. Each repetition is known as a pass or iteration.There are two types of loops– those that repeat an action a predefined number of times and those that perform the action until the program determines that it needs to stop. In this post, we are examining Python’s for loop, the control statement that most easily supports definite iteration.
The general structure of a for loop is as follows:

Below is an example of a for loop with different conditional statements.


The first line of the loop is called the loop header. After the conditional statement, there is a colon to denote that everything indented underneath that line, is part of the loop’s functions. This is the loop body. It is essential that the loop body must be correctly indented and aligned into the same column. The statements in the loop body are executed in sequential order.
Loops that count through a range of numbers are also called count-controlled loops. The value of the count on each pass is often used in computations. To count from an explicit lower bound, anything other than a starting count of 0, the programmer must supply a second integer expression in the loop header. You can see the differences below. Notice that both codes produce the same output.


The for loop is not only easy to write, but also easy to do correctly. Once the syntax is correct, the only other problem that may arise is an off-by-one error. This is the result of when a programmer incorrectly specifies the upper bound of the loop.