1 What is a nested loop
The so-called nested loop is that the main part of an outer loop is an inner loop . Inner loop or outer loop can be any type , for example while Cycle or for loop . for example , external for
A loop can contain a while loop , vice versa . The outer loop can contain multiple inner loops . There is no limit to the cycle chain .
In nested loops , The number of iterations will be equal to the number of iterations in the outer loop multiplied by the number of iterations in the inner loop . In each iteration of the outer loop , The inner loop performs all its iterations .
For each iteration of the outer loop , The inner loop restarts and completes its execution before the outer loop can continue to the next iteration . Nested loops are often used to handle multidimensional data structures , For example, print a two-dimensional array , Iterates over a list that contains nested lists . Nested loops are part of the control flow statement , Can help you understand
Python Basic knowledge of .
2 Python nesting for loop
stay Python in ,for Loops are used to iterate sequences , Example list , character string , tuple , And other iteratable objects , For example, scope . stay Python Use nesting in for Circular syntax ：
# outer for loop for element in sequence # inner for loop for element in
sequence: body of inner for loop body of outer for loop
In this example , We are for Used in the loop for loop . In this case , We print the multiplication table of the first ten numbers .
* external for Recycling range() First ten digits of function iteration .
* For each external number , inside for The loop will be executed ten times .
* In the body of the inner loop , We will print the product of the external number and the current number .
* The inner loop is just the main body of the outer loop .
Examples ： Write a nested for Loop program to Python Print multiplication table in .
# outer loop for i in range(1, 11): # nested loop # to iterate from 1 to 10
for j in range(1, 11): # print multiplication print(i * j, end=' ') print()
* In this program , external for The loop is from 1 reach 10 Iterative number . range() return 10 Number . So the total number of iterations of the outer loop is 10.
* Nested in the first iteration , The number is 1. Next time , It is 2. And so on , until 10.
* next , For each iteration of the outer loop , The inner loop will be executed ten times . The internal loop will also be executed 10 second , Because the multiplication table we print is at most 10.
* In each iteration of the internal loop , We calculated the multiplication of two numbers .
2.1 Nested loop print pattern
Another of the most common uses of nested loops is to print various star and number patterns . Let's see how to use nested loops in Python Print the following modes in .
rows = 5 # outer loop for i in range(1, rows + 1): # inner loop for j in
range(1, i + 1): print("*", end=" ") print('')
* In this program , The outer loop is the number of lines printed .
* The number of rows is five , So the outer loop will be executed five times .
* next , The inner loop is the total number of columns in each row .
* For each iteration of the external loop , The column count increases 1.
* In the first iteration of the outer loop , The number of columns is 1, Next time 2. And so on .
* The internal loop iteration is equal to the number of columns .
* In each iteration of the internal loop , We print star.
2.2 stay for In loop while loop
Using another type of loop in one loop is very common and helpful . We can for Place one in the loop while loop . Suppose we want to repeat each name in the list five times ：
* here , We will use external for Loop iteration list .
* Outer layer for Loop each iteration , Inner layer for Loop execution 5 second , Print current name 5 second . names = ['Kelly', 'Jessa', 'Emma'] #
outer loop for name in names: # inner while loop count = 0 while count < 5:
print(name, end=' ') # print(name) # increment counter count = count + 1 print()
2.3 practice ： Print a with 5 that 's ok 3 Rectangular pattern of column stars
Print the following star rectangle ：
# 5 rows for name in range(5): # 3 column for j in range(3): print('*',
3 Breaking nested loops
break Statement is used to exit a loop inside a loop . If used within a nested loop break sentence （ Cycle in another cycle ）, It will terminate the innermost loop .
In the following example , We have two cycles . external for Recycling range() First four digits of function iteration , inside for The loop also iterates over the first four digits .
If the external number is the same as the current number of the internal cycle , Then interrupt the internal （ nesting ） loop .
for i in range(4): for j in range(4): if j == i: break print(i, j)
4 Continue nested loop
continue Statement skips the current iteration and moves to the next iteration . stay Python in , When encountered in the loop continue
Statement time , It skips all statements below it and immediately jumps to the next iteration .
In the following example , We have two cycles . external for
Loop iteration first list , The inner loop also iterates over the second numeric list . If the external number is the same as the current number of the internal cycle , Then move to the next iteration of the internal loop .
first = [2, 4, 6] second = [2, 4, 6] for i in first: for j in second: if i ==
j: continue print(i, '*', j, '= ', i * j)
5 Single line nested loops understood using lists
for example , If you have two lists and want to get all their combinations , To achieve this , You need to use two nested loops , As described below .
first = [2, 3, 4] second = [20, 30, 40] final =  for i in first: for j in
second: final.append(i+j) print(final)
You can write faster using list compression and nested loops , More compact code , As shown below .
first = [2, 3, 4] second = [20, 30, 40] final = [i+j for i in first for j in
Coding ideas ：
* first , Write an external for loop , It iterates over the first list , as [for i in first].
* next , Write an internal loop , It iterates over the second list after the external loop , for example [for i in first for j in second].
* last , Calculate the sum of outer and inner numbers , as [i+j for i in first for j in second].
* last , Store the results in a new list , for example final = [i+j for i in first for j in second].
Let's look at other examples ：
In this example , We will use two in the list for loop , The end result will be a list . We will not include the same number in each list . We will use if Filter them conditionally .
final = [[x, y] for x in [10, 20, 30] for y in [30, 10, 50] if x != y]
6 Python Nesting in while loop
stay Python in ,while A loop statement repeats a block of code when a particular condition is true . When the number iteration is not fixed , We use while loop . In this section , We'll learn how to work in another
while Use in circulation while loop . stay Python Write nested while The syntax of the loop statement is as follows ：
while expression: while expression: statement(s) statement(s)
In the following example , We will print before each line 10 Number 5 second .
i = 1 while i <= 5: j = 1 while j <= 10: print(j, end='') j = j + 1 i = i + 1
6.1 While In cycle for loop
Sometimes it's helpful to use one loop in another . We can while Put one in the loop for loop . Suppose we want to print from 1 reach 100 All the perfect numbers .
* here , We will use while Before loop iteration 100 Number .
Outside while In each iteration of the loop , inside for Cycle from 1 To current external digital execution , To check if the current number is perfect .（ Perfect number is a mathematical concept , Interested readers can further inquire ）
print('Show Perfect number fom 1 to 100') n = 2 # outer while loop while n <=
100: x_sum = 0 # inner for loop for i in range(1, n): if n % i == 0: x_sum += i
if x_sum == n: print('Perfect number:', n) n += 1
7 When Python Using nested loops in ?
* When you have nested arrays or lists that need to loop through the same function , Nested loops are convenient .
* When you want to print different star and number patterns using rows and columns .
Remember time complexity . Let's pass Python Nested in for An example of how a loop works to understand this . We use for A cyclic iterative sequence or a given element that can be iterated .
Just like I'm on the list . The time complexity here is
O(n), Because we are iterating over all the items in the list . Perform steps （ iteration ） The number of determines the time complexity of the loop . When you use nested loops and there are no external and internal loops if
Run time under conditions , The time complexity is O(n^2), Because for all n Elements , The code will execute n second .
numbers = [[1, 2, 3], [4, 5, 6]] cnt = 0 for i in numbers: for j in i:
print('iteration', cnt, end=': ') print(j) cnt = cnt + 1
If you give a condition in the inner loop , This condition will stop executing after some elements , And does not execute all of the internal or external loops n Second iteration , Then its time complexity will be less .
Use nested loops when you don't have a better choice , Remember that writing efficient and compact code is far better than writing complex code .