Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

As you can see, the for loop construct has no problem handling this slight change. The loop
evaluates the variable top_number as 10 , and the iteration processes correctly for that number.


Iterating Using the range Function


Instead of listing all the numbers individually in a data list, you can use the range function to create
a contiguous number list for you. The range function really shines when it’s used in loops.


By the Way: A Function or Not?
The range function is not really a function. It is actually a data type that represents an
immutable sequence of numbers. However, for now, you can just think of it as a
function.

To include the range function in a loop, you replace your numeric data list as shown in Listing 7.10.
The single number between parentheses is called the stop number. In this example, the stop number is
set to 5. Notice that the range of numbers starts at 0 and ends at 4.


LISTING 7.10 Using the range Function in a for Loop


Click here to view code image


>>> for the_number in range (5):
... print (the_number)
...
0
1
2
3
4
>>>

In Listing 7.10, using the range function causes a data list of numbers to be created: [0, 1, 2,
3, 4]. The range function, by default, starts at 0 and then produces a list of numbers all the way
up to the stop number minus 1. Thus, with 5 listed as the stop number, the range function stops
producing numbers at 5 minus 1 , or 4.


Did You Know: Integers Only
The range function can only accept integer numbers as arguments. No floating points
or character strings are allowed.

You can alter the behavior of the range function by including a start number. The syntax looks
like this:


range(start, stop)

and is demonstrated in Listing 7.11.


LISTING 7.11 Using a Stop Number in a range Function

Free download pdf