Question 5.21: Repeating Instructions an Exact Number of Times You need to ......

Repeating Instructions an Exact Number of Times

You need to repeat some program code an exact number of times.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the Python for command and iterate over a range.

For example, to repeat a command 10 times, use the following example:

>>> for i in range(1, 11):
… print(i)

1
2
3
4
5
6
7
8
9
10
>>>

Discussion

The second parameter in the range command is exclusive; that is, to count up to 10, you must specify a value of 11.

See Also

If the condition for stopping the loop is more complicated than simply repeating a number of times, see Recipe 5.21.

If you are trying to repeat commands for each element of a list or dictionary, see Recipes 6.7 or 6.15, respectively.

Related Answered Questions

Question: 5.24

Verified Answer:

Create a function that groups together lines of co...
Question: 5.23

Verified Answer:

Use the Python break statement to exit either a wh...
Question: 5.22

Verified Answer:

Use the Python while statement. The while statemen...
Question: 5.20

Verified Answer:

Use one of the logical operators: and, or, and not...
Question: 5.19

Verified Answer:

Use one of the comparison operators: <, >, &...
Question: 5.17

Verified Answer:

Use the upper or lower function as appropriate. Fo...
Question: 5.18

Verified Answer:

Use the Python if command. The following example w...
Question: 5.15

Verified Answer:

Use the Python [:] notation. For example, to cut o...
Question: 5.14

Verified Answer:

Use the find Python function. For example, to find...