• No results found

A nested loop is a loop statement that is inside a loop statement. For example, a for loop used within the code block of a while loop would be a nested loop. Listing 7.22 shows a script that uses nested loops. It has a for loop that contains three while loops in the for loop’s code block. script0703.py is a slight improvement over the script you wrote in the last “Try it Yourself” section of this hour.

Listing 7.22 A Nested Loop in script0703.py

Click here to view code image

pi@raspberrypi:~$ cat py3prog/script0703.py

# script0703.py - Demonstration of a nested loop.

# Author: Blum and Bresnahan

#

###########################################################

#

# Find out how many club member names need to be entered

names_to_enter=int(input(“How many Python club member names to enter? “))

#

# Loop to enter names:

for member_number in range (1, names_to_enter + 1):

print()

print(“Member #” + str(member_number))

#

first_name=”” # Intialize first_name middle_name=”” # Intialize middle_name last_name=”” # Intialize last_name

#

### Loop to get first name while first_name == ””:

first_name=input(“First Name: “)

#

### Loop to get middle name while middle_name == ””:

middle_name = input(“Middle Name: “)

#

### Loop to get last name while last_name == ””:

last_name = input(“Last Name: “)

#

# Display a member’s full name print()

print (“Member #”, member_number, “is”, first_name, middle_name, last_name) pi@raspberrypi:~$

The first improvement is that the main while loop has been replaced by a for loop.

Using a for loop eliminates the need to keep track of the number of names that have been entered along the way.

Nested within the for loop are three while loops. These while loops improve the input verification by ensuring that a script user cannot accidentally leave a name blank.

In Listing 7.23, you can see the new script run and an example of the input verification improvement. When the script user accidently presses the Enter key twice instead of

entering Raz’s middle name, the script loops back to the input statement and asks again.

Listing 7.23 Output of script0703.py

Click here to view code image

pi@raspberrypi:~$ python3 py3prog/script0703.py How many Python club member names to enter? 1 Member #1

First Name: Raz Middle Name:

Middle Name:

Middle Name: Berry Last Name: Pi

Member # 1 is Raz Berry Pi pi@raspberrypi:~$

Listings 7.22 and 7.23 show a very simple example of a nested loop. Nested loops often are used in Python scripts for processing data tables, running image algorithms,

manipulating games, and so on.

Summary

In this hour, you got a little loopy. You learned how to create a for loop and a while loop. Also, you were introduced to concepts such as pretesting, sentinels, and input verification. Finally, you got to try both a for loop and a while loop and look at a nested loop. In Hour 8, “Using Lists and Tuples,” you will be moving on from structured commands and investigating lists and tuples.

Q&A

Q. Does Python v3 have the xrange function?

A. Yes and no. In Python v2, the xrange function was available, along with the

range function. In Python v3, the range function is the old xrange function and the Python v2 range function is gone. The creators of Python made this change because xrange is more efficient in terms of memory usage than range.

Unfortunately, to convert a Python v2 xrange to Python v3, you need to remove the x in front of the word range.

Q. Is it poor form to use a break statement in a loop?

A. This depends on who you ask. If you can avoid using a break, that is best.

However, sometimes you cannot determine another method, so you have to use break. Most hard-core programmers consider using break to be poor form.

Q. I am running my Python script, and it is stuck in an infinite loop! What do I do?

A. You can stop the execution of a Python script by pressing Ctrl+C. If this doesn’t work, try Ctrl+Z.

Workshop Quiz

1. A for loop is a count-controlled loop, and a while loop is a condition-controlled loop. True or false?

2. A count-controlled loop means the loop continues as long as a. The count returns a True code.

b. The count returns a False code.

c. There are items to be processed.

3. Which type of loop is pretested?

4. What is wrong with the following code’s syntax?

for a_number in [5, 10, 1]

print(a_number)

5. What is wrong with the following code’s syntax?

while True:

print (“Hello World”)

6. A(n) __________ loop is a loop that does not end.

7. A(n) __________ __________ is any predetermined value that is used to indicate the data’s end.

8. When a break command is executed in a while loop, Python statements in the else clause are skipped. True or false?

9. What is wrong with the following code’s syntax?

Click here to view code image

for the_number in [‘A’,‘B’,‘C’,‘A’,1]:

print(the_number)

10. If you want to produce a list of numbers for a for loop, starting at 1 and going to 10, with a step of 1, which range statement should you use?

a. range(10)

b. range(1, 10, 1) c. range(1, 11)

Answers

1. True. A for loop iterates a set number of times, and thus each iteration is counted. A while loop iterates until a certain condition is met, and then it stops.

2. c. A count-controlled loop iterates for every item listed.

3. A while loop is a pretested loop because the condition test statement is run before the statements in the loop’s code block are executed.

4. A colon (:) is missing after the ending bracket (]). The code should be written as follows to be correct:

for a_number in [5, 10, 1]:

print(a_number)

5. The while loop’s print statement is not properly indented. The code should be written as follows to be correct:

while True:

print (“Hello World”)

6. An infinite loop is a loop that does not end.

7. A sentinel value is any predetermined value that is used to indicate the data’s end.

8. True. A break command executed within a while loop causes any Python statements in the else clause to be skipped over (not executed).

9. This is a trick question. Nothing is wrong with the code’s syntax! It might be odd to include two letter A’s and a number, but the code is correct as is:

Click here to view code image

for the_number in [‘A’,‘B’,‘C’,‘A’,1]:

print(the_number)

10. c. The range(1, 11) produces the following list of numbers for the for loop to use: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Remember that the last number, the stop number, in the range function is not included in the output list.

Part III: Advanced Python

Hour 8. Using Lists and Tuples

What You’ll Learn in This Hour:

Working with tuples and lists Using multidimensional lists

Building lists with comprehensions

When you work with variables, sometimes it comes in handy to group data values together so you can iterate through them later in your script. You can’t easily do that with separate variables, but Python provides a solution for you.

Most programming languages use array variables to hold multiple data values but point to them using a single indexed variable name. Python is a little different in that it doesn’t use array variables. Instead, it uses a couple other variable types, called lists and tuples. This hour examines how to use lists and tuples to store and manipulate data in Python scripts.