• No results found

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. However, 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 numeric data list to be created: [0, 1, 2, 3, 4]. The range function, by default, starts at 0 and then produces a number list 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 accept only 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 Start Number in a range Function

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 through 5 to be used in the loop, you can use range (1, 5+1) as your range statement. At a glance, you 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

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 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:

1. If you have not already done so, power up your Raspberry Pi and log in to the system.

2. If you do not have the GUI started automatically at boot, start it now by typing startx and pressing Enter.

3. Open a terminal by double-clicking the Terminal icon.

4. 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.

5. Type the following code into the nano editor window, pressing Enter at the end of each line:

Watch Out!: 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.

Click here to view code image

# script0701.py - The Secret Word Validation.

# Written by <your name here>

# Date: <today’s date>

#

############ Define Variables ###########

#

max_attempts=3 #Number of allowed input attempts.

the_word=‘secret’ #The secret word.

#

############# Get Secret Word ################

#

print()

for attempt_number in range (1, max_attempts + 1):

secret_word=input(“What is the secret word? “) if secret_word == the_word:

print()

print(“Congratulations! You know the secret word!”) print()

break # Stops the script’s execution.

else:

print()

print(“That is not the secret word.”)

print(“You have”, max_attempts - attempt_number, “attempts left.”) print()

Watch Out!: Proper Indentation

Remember that when you use a text editor, you need to be sure you do the

indentation properly. If you do not indent the for and the if code blocks properly, Python will give you an error message. Refer to the section “Watching for a Few

‘Gotchas,’” earlier this hour, for help on this, if needed.

6. Write out the modified script you just typed in the text editor by pressing Ctrl+O.

Press Enter to write out the contents to the script0701.py script.

7. Exit the nano text editor by pressing Ctrl+X.

8. Type python3 py3prog/script0701.py and press Enter to run the script. The first time you run the script, answer the question correctly by entering secret. You should see output similar to that shown in Figure 7.2.

Figure 7.2 The script0701.py output with the correct answer.

The script stops after you enter the correct answer because of the break

statement. The break statement causes the loop to terminate. In other words, it lets you “break out” of the loop.

9. Type python3 py3prog/script0701.py again and press Enter to run the script. This time, answer the question incorrectly, answering anything except secret. You should see output similar to that shown in Figure 7.3.

Figure 7.3 The script0701.py output with incorrect answers.

Input verification is an important tool. The little script you just created is a small example of what you can do with a for loop to verify user input. A while loop, as you’ll see next, is another type of loop to use for input verification in Python scripts.