[Python] loop statement② ( while nested loop | code example - while nested loop )





1. while nested loop




1. While nested loop syntax


The while nested loop is to nest the inner loop in the outer loop;

While nested loop syntax format:

while 外层循环条件:
	外层循环操作1
	外层循环操作2

	while 内存循环条件:
		内层循环操作1
		内层循环操作2

The while nested loop is also based on space indentation, which in Python determines ;

The loop operation of the outer loop is indented with four spaces in front,

The while keyword of the inner loop and the statement where the loop condition is located are indented with four spaces in front ,

Loop operations for memory loops are indented with eight spaces in front ;


Notice :

  • Pay attention to the setting of the control , and do not have an infinite loop;
  • The more loop levels, the more loop control variables involved;

2. Code example - while nested loop



Code example:

"""
while 嵌套循环代码示例
"""

# 外层循环 循环控制变量
i = 1

# 外层循环 循环条件
while i <= 3:
    # 外层循环操作
    print(f"第 {
      
      i} 次外层循环")

    # 内层循环 循环控制变量
    j = 1
    # 内层循环条件
    while j <= 2:
        # 内层循环操作
        print(f"    第 {
      
      j} 次内层循环")
        # 内层循环控制变量自增
        j += 1

    # 外层循环控制变量自增
    i += 1

# 如果要统计循环次数, 使用 i - 1,
# 因为最后一次运行 i 自增为 4 ,
# 不符合 i <= 3 的要求 , 终止循环
# 循环次数为 i - 1
print(f"循环次数 : {
      
      i - 1}")

Results of the :

1 次外层循环
    第 1 次内层循环
    第 2 次内层循环
第 2 次外层循环
    第 1 次内层循环
    第 2 次内层循环
第 3 次外层循环
    第 1 次内层循环
    第 2 次内层循环
循环次数 : 3

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/130888402