3.8 for Statement

Like the while statement, the for statement allows you to repeat an action or several actions. The for statement performs its action(s) for each item in a sequence of items. For example, a string is a sequence of individual characters. Let’s display 'Programming' with its characters separated by two spaces:

In [1]: for character in 'Programming':
   ...: print(character, end=' ')
   ...:
P r o g r a m m i n g

The for statement executes as follows:

  • Upon entering the statement, it assigns the 'P' in 'Programming' to the target variable between keywords for and in—in this case, character.

  • Next, the statement in the suite executes, displaying character’s value followed by two spaces—we’ll say more about this momentarily.

  • After executing ...

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.