The repetition structure, or loop, processes one or more instructions repeatedly. The repeatable instructions in a loop are called the loop body. When a loop’s condition evaluates to true, the instructions in the loop body are processed. Otherwise, the instructions are skipped and processing continues with the first instruction after the loop. After each processing of the loop body (iteration), the loop’s condition is reevaluated to determine if the instructions should be processed again.
It contains four elements:
Python has while and for loop. These are pretest loop which is an entrance-controlled loop where the condition is evaluated before the instructions in the loop are processed. If the condition is false, the statements in the loop body will never be executed.
Some loops require the user to enter a special sentinel value to end the loop. Sentinel values should be easily distinguishable from the valid data recognized by the program.
A loop whose instructions are processed indefinitely is called an infinite loop or endless loop .
while statement is used to create a while loop.
Syntax:A for loop uses the for statement to code any pretest loop. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Syntax:A counter can be used to control the loop instead of using a sentinel value. A counter is a numeric variable used for counting something. An accumulator is a numeric variable used for accumulating (adding together) multiple values. It is used to perform calculations such as total or average.
Two tasks are associated with counters and accumulators:
A break statement forces an immediate break or exit from switch, while, for, and do-while statements. It is useful for breaking out of loops when an unusual condition is detected
A continue statement applies to while, do-while, and for statements; causes the next iteration of the loop to begin immediately. It is useful for skipping over data that should not be processed in this iteration while staying within the loop