第六章第4讲:嵌套与可变循环

时间:2022-09-08 11:46:17

1. 嵌套循环

# 嵌套循环
for multiplier in range (5,8):
    for i in range (1,5):
        print(i,"x",multiplier,"=",i*multiplier)
    print("============")

结果:

1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
4 x 5 = 20
============
1 x 6 = 6
2 x 6 = 12
3 x 6 = 18
4 x 6 = 24
============
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
============

 2. 可变循环

案例1:

# 打印星号(*)的格式,由用户输入
numstars = int(input("How many stars do you want:"))
for i in range(numstars):
    print("*",end="")

结果:

How many stars do you want:7
*******

 

注:python中“end=”用法:例如print(“#”,end=" \n"),默认换行,print(“*”,end=" ")则在循环中不换行

案例2:双重嵌套

numlines = int(input("How many lines of '*'do you want:"))
numstars = int(input("How many '*'do you want:"))
for lines in range(numlines):
    for stars in range(numstars):
        print("*",end="")
    print()
    print("===========")

结果:

How many lines of '*'do you want:2
How many '*'do you want:7
*******
===========
*******
===========

 案例3:三重嵌套

注意:嵌套层次不要太多,尽量控制在2层以内。

numblocks = int(input("How many blocks of '*'do you want:"))
numlines = int(input("How many lines of '*'do you want:"))
numstars = int(input("How many '*'do you want:"))
for blocks in range(numblocks):
    for lines in range(numlines):
        for stars in range(numstars):
            print("*",end="")
        print()
    print("===========")

结果:

How many blocks of '*'do you want:2
How many lines of '*'do you want:3
How many '*'do you want:7
*******
*******
*******
===========
*******
*******
*******
===========