for循环:
python中的for循环是用来迭代容器中的每一个元素的,而不是c,java中理解那个循环;
for 零时变量 in 容器:
print(零时变量) #每一个迭代出的元素
range 全局函数:
range(num) # [0, num)区间内所有整数
range(start, end) #[start, end)区间内所有整数
range(start, end, step) # 默认步长是1,但是可以通过第三个参数修改步长
案例1:
*
**
***
****
*****
layer = int(input("请输入你想打印的行数:")) for i in range(0, layer+1):for j in range(0, i):print("*", end="")print()
案例2:
*
***
*****
*******
*********
layer = int(input("请输入你想打印的行数:")) for i in range(0, layer):for j in range(0, (2 * i) + 1):print("*", end="")print()
案例3:
*
* *
* * *
* * * *
* * * * *
方法一:
for i in range(1, layer + 1):#打印空格的个数for j in range(layer - i):print(" ", end=" ")#打印*的个数for j in range(i):print("*", end=" ")print()
方法二:
for i in range(1, layer + 1):# 打印空格的个数print(" " * (layer - i), end=" ")# 打印*的个数print("*" * i,)
案例4:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
for i in range(1, layer + 1):#打印空格的个数for j in range(layer - i):print(" ", end=" ")#打印*的个数for j in range(2 * i - 1):print("*", end=" ")print()
案例5:
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
for i in range(layer, 0, -1):#打印空格的个数for j in range(layer - i):print(" ", end=" ")#打印*的个数for j in range(2 * i - 1):print("*", end=" ")print()
案例6:
*
***
*****
*******
*********
*******
*****
***
*
layer = int(input("请输入一个奇数:")) while layer % 2 == 0:layer = int(input("请输入一个奇数:")) for i in range(1, layer // 2 + 1):print(" " * (layer - i), end=" ")print("*" * (2 * i - 1)) for i in range(layer // 2 - 1, 0, -1):print(" " * (layer - i), end=" ")print("*" * (2 * i - 1))
实验七:(存在问题)
layer = int(input("请输入一个奇数:")) while layer % 2 == 0:layer = int(input("请输入一个奇数:")) for i in range(0, layer // 2 + 2):print(" " * (layer - i), end=" ")for j in range(2 * i + 1):if j == 0 or j == 2 * i:print("*", end=" ")else:print(" ", end=" ")print() for i in range(layer // 2 - 1, -1, -1):print(" " * (layer - i), end=" ")for i in range(2 * i + 1):if j == 0 or j == 2 * i:print("*", end=" ")else:print(" ", end=" ")