Menu Close


Python: repetition

Repetition statement is a block of code containing several statements that can be executed multiple times. The number of times is determined by a control condition. Sometimes the repetition is forever and this is called infinite loop. There are 2 kind of repetition statements in Python: “while” and “for”.

While statement

The while statement is used for repeated execution as long as an expression is true:

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false the suite of the else clause is executed and the loop terminates. The second suite is optional and may not be present.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

For example:

The previous examples will print 100 times “forever young”, then will print “I was young forever”. So the break statement has stopped the infinite loop.

For statement

The for statement in Python differs from what you may be used to in Java or C or Pascal. Rather than always iterating over an arithmetic progression of numbers,  Python iterates over the items of any collection of items.

Will print:

Range() function

If you need to iterate over a finite sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions that can be used as a collection of numbers:

Break and continue

Forcing a repetition block to break or to continue is possible in a for loop or in a while loop. This can be done in a combination with an if statement.

Will print:

v = 6

This example has demonstrate the for loop, the continue and the break.

Else branch

The official declaration of for loop statement is difficult to read but we can see the for statement also have an “else” part like the while loop.

This means you can write something like this:

Note: else branch is executed when the range is finished or break is used. However not many developers knows about this feature. It can be useful to improve the program readability if the loop is very long.


Read next: Data types