Why use the range function to iterate a for loop for a specific count?


#1

Question

This exercise uses a range() function to cause the for loop to iterate a specific number of times. Why can’t the number of times to iterate a for loop be specified without range()?

Answer

In Python, a for loop is intended to iterate over a collection of items, unlike other languages where it is tied to a variable which has an initial value, an increment, and a test for the final value. Since the for loop is expecting a collection or list to iterate over, the range() function is used to provide a list of numbers. This list of numbers is used to cause the for loop to iterate the desired number of times. It’s important to remember that the list generated by range() defaults from 0 to one less than the number specified.

The following example uses range() with a starting number of 1 to print the squares of the numbers 1 through 10.

for number in range(1,11):         
    print(number ** 2)