Menu Close

Articles

Python: repetition

Repetition 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: In this case else: branch is never executed, due to early break. However, in normal case if your statement is not early terminated, the else: branch can be useful. Try to copy the example and comment out the break.

Comprehension

There is a cool notation available in Python that help you avoid writing loops. This is a “syntax sugar” for a repetitive statement. It is very similar to “set builder” notation that we learn in Mathematics:

Example:

Check this example live: comprehension

Note: Comprehension notation is “declarative” not “structured”. Python is a hybrid language, it has multiple paradigms available, so “there are more then one way to skin a goat”.  You chose the one best suited to your project. It is considered a good practice to write “pythonish” code using this kind of notation instead of a loop.

Read next: Functions