8
>>>
You can use the range function to produce a list of numbers that goes “backward.” You accomplish
this by making your step number negative. Of course, you have to carefully think through your start
and stop numbers, too. Listing 7.14 produces the same results as Listing 7.13, only backward. Notice
the difference in the range arguments in Listing 7.14 and Listing 7.13.
LISTING 7.14 Stepping “Backward” with a range Function
Click here to view code image
>>> for the_number in range (8,1,-2):
... print (the_number)
...
8
6
4
2
>>>
Now that you have a taste of the for loop, it’s time to try out a practical for loop example for
yourself.
Try It Yourself: Validate User Input with a for loop
An important part of obtaining input from a script user is validating the input. This is
called input verification. In the script you write in the following steps, you are going
to allow the script user three attempts to get the input right. Also, you are going to get a
chance to try something new, a break. Unfortunately, you don’t get to pour a cup of
tea with this kind of a break. Follow these steps:
- If you have not already done so, power up your Raspberry Pi and log in to the
system. - If you do not have the LXDE GUI started automatically at boot, start it now by typing
startx and pressing Enter. - Open the LXTerminal by double-clicking the LXTerminal icon.
- At the command-line prompt, type nano py3prog/script0701.py and press
Enter. The command puts you into the nano text editor and creates the file
py3prog/script0701.py. - Type the following code into the nano editor window, pressing Enter at the end of
each line:
By the Way: Be Careful!
Be sure to take your time here and avoid making typographical errors. You can
make corrections by using the Delete key and the up- and down-arrow keys.