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

(singke) #1

Click here to view code image


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

Variables can be used in place of the numbers in the range function. Listing 7.12 shows how this
works.


LISTING 7.12 Using Variables in a range Function


Click here to view code image


>>> start_number = 3
>>> stop_number = 6
>>> for the_number in range (start_number, stop_number):
... print (the_number)
...
3
4
5
>>>

By the Way: Range of Expressions
You can use a mathematical expression as your start or stop number. This is a slick
trick to help add clarity to your Python statements. For example, if you want the
numbers 1 to 5 to be used in the loop, you can use range (1, 5+1) as your
range statement. At a glance, you will see the number where the range function
stops.

To change the increment of the number list produced by the range function, you include a step number
in your range arguments. By default, the range function increments the numbers in the list by 1. By
adding a step number, using the format range (start, stop, step), you can modify this
increment. In Listing 7.13, the increment is changed from the default of 1 to 2.


LISTING 7.13 Using a Step Number in a range Function


Click here to view code image


>>> for the_number in range (2,9,2):
... print (the_number)
...
2
4
6
Free download pdf