While loops are used for counting a specific number of iterations, and for loops are used to iterate over all elements of a container. The range() function allows counting in for loops as well. range() generates a sequence of integers between a starting integer that is included in the range, an ending integer that is not included in the range, and an integer step value. The sequence is generated by starting at the start integer and incrementing by the step value until the ending integer is reached or surpassed.
The range() function can take up to three integer arguments.
range(Y)
generates a sequence of all non-negative integers less than Y.
Ex: range(3)
creates the sequence 0, 1, 2.
range(X, Y)
generates a sequence of all integers >= X and < Y.
Ex: range(-7, -3)
creates the sequence -7, -6, -5, -4.
range(X, Y, Z)
, where Z is positive, generates a sequence of all integers >= X and < Y, incrementing by Z.
Ex: range(0, 50, 10)
creates the sequence 0, 10, 20, 30, 40.
range(X, Y, Z)
, where Z is negative, generates a sequence of all integers <= X and > Y, incrementing by Z.
Ex: range(3, -1, -1)
creates the sequence 3, 2, 1, 0.
Range | Generated sequence | Explanation |
---|---|---|
|
| Every integer from 0 to 4 |
|
| Every integer from 0 to 4 |
|
| Every integer from 3 to 6 |
|
| Every integer from 10 to 12 |
|
| Every 1 integer from 0 to 4 |
|
| Every 2nd integer from 0 to 4 |
|
| Every 1 integer from 5 to 1 |
|
| Every 2nd integer from 5 to 1 |
!!!As a general rule:!!!
Use a for loop when the number of iterations is computable before entering the loop, as when counting down from X to 0, printing a string N times, etc.
Use a for loop when accessing the elements of a container, as when adding 1 to every element in a list, or printing the key of every entry in a dict, etc.
Use a while loop when the number of iterations is not computable before entering the loop, as when iterating until a user enters a particular character.
These are not hard rules, but general guidelines.