现在来尝试一个可变嵌套循环。这就是一个嵌套循环,只不过其中一个或多个循环在 range
函数中使用了变量。代码清单 11-2 给出了一个例子。
代码清单 11-2 一个可变嵌套循环
numLines = int(raw_input ('How many lines of stars do you want? '))numStars = int(raw_input ('How many stars per line? '))for line in range(0, numLines): for star in range(0, numStars):print '*', print
运行这个程序来看它的作用,你会看到类似这样的结果:
>>> ============================ RESTART ============================>>>How many lines of stars do you want? 3How many stars per line? 5***************
前两行询问用户想要多少行,以及每行希望有多少个星号。程序使用变量 numLines
和 numStars
记住这些答案。接下来有两个循环:
内循环(
for star in range (0, numStars):
)打印每个星号,对每一行上的每个星号分别运行一次;外循环(
for line in range (0, numLines):
)对每行星号分别运行一次。
需要用第二个 print
命令开始新的一行星号。如果没有这个命令,由于第一个 print
语句中有逗号,所有星号都会打印到同一行上。
甚至可以有“嵌套嵌套循环”(或双重嵌套循环),就像代码清单 11-3 这样。
代码清单 11-3 利用双重嵌套循环生成星号块
numBlocks = int(raw_input ('How many blocks of stars do you want? '))numLines = int(raw_input ('How many lines in each block? '))numStars = int(raw_input ('How many stars per line? '))for block in range(0, numBlocks): for line in range(0, numLines):for star in range(0, numStars): print '*',printprint
会得到下面的输出:
>>> ======================= RESTART =======================>>>How many blocks of stars do you want? 3How many lines of stars in each block? 4How many stars per line? 8* * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * ** * * * * * * *
我们称这个循环嵌套“深度为 3”。