Repetition in Python may be done using the while statement.

Recall that indentation is used to indicate groups of statements.

Indentation will indicate the statement or groups of statements that will be executed repeatedly.

Terminology note: Programmers often call repetition statements loops.

while Loop - Python, Generic

Python while statements have the form:

while condition:
   statement_1 # Executes if the loop condition is true
   statement_n # Go back to loop condition after this statement
statement_after_loop # Executes after the loop condition is false

The indented statements are executed if the condition is true, otherwise execution continues with the statement that follows the indented group of statements.

After the last statement of the indented group is executed execution automatically goes back and evaluates the condition again.

Indentation is used to denote the group of statements that may be executed repeatedly.

Note the required colon after the condition.

while Loop - Python, Example

Example, output the numbers 1 through 10:

ctr = 1
while ctr <= 10:
   ctr = ctr + 1

Indentation is used to denote the group of statements that are be executed repeatedly.

Counter-Controlled Loops

Counter-controlled use a counter variable that controls the iteration.

ctr = 1 # Initialize counter - Happens once
while ctr <= 10:
   ctr = ctr + 1

Usually the counter variable modification is the last thing in the loop body so the variable has the same value through the loop body as it had in the condition.

The counter variable may count up or down by ones or two, etc. according to the counter variable modification and the condition.

Sentinel-Controlled Loops

The alternative to counter-controlled is a sentinel-controlled loop.

In this sort of loop the condition "looks for" something to be true, or not.

Python-like pseudocode example:

number = INPUT_NUMBER # Input is discussed later
while number >= 0: # Condition - Happens before each repetition

The number of repetitions is controlled by an input value, for example.

A counter variable still may be present but the counter is not used to control the number of iterations in this case.