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 out 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, there
are times when 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. What type of loop is pretested?
3. 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. 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.
3. Answer c is correct. 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.