Hardware Reference
In-Depth Information
A nested loop is a loop inside another loop. The first loop is called the outer
loop , and the second loop is called the inner loop . Loops are nested in Python by
indenting the second loop another level. You can nest loops inside loops inside
loops any number of times.
If you accidentally leave some blank lines at the end of your data file, these will
be read in and interpreted by your Python program. Fortunately it doesn't make
your program crash, but you might see some redundant extra blocks at the end
of the maze as a result.
DIGGING INTO THE CODE
In earlier adventures, you experimented with Python lists and learned that a list
is just a collection of zero or more items stored in numbered slots. Many func-
tions built into the Python language provide data in the form of a list, and you
have just met two new ones in the maze builder program.
This line of code is the first one:
for line in f.readlines():
Remember that f is a file handle—something you can grab hold of to gain
access to an open file. Usefully, the file type in Python has a readlines()
function built into it. This simply reads every line of the file and appends (adds)
each line to the end of the list. You may also remember from earlier adventures
that, when it's given a list, the for statement in Python will loop through all the
items in the list.
All the for statement does is read every line in the file into a list, and then loop
through them one at a time. Each time around the for loop, the line variable
(the loop control variable) holds the next line of data.
If you have a file with three lines in it like this:
line one
line two
line three
 
Search WWH ::




Custom Search