需要掌握条件控制语句和循环语句
if语句的一般形式如下所示:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
"""
如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
如果 "condition_1" 为False,将判断 "condition_2"
如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
如果 "condition_2" 为False,将执行"statement_block_3"块语句
"""
for 循环可以遍历任何可迭代对象,如一个列表或者一个字符串。
for循环的一般格式如下:
for <variable> in <sequence>:
<statements>
else:
<statements>
如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列,例如:
for i in range(5) :
print(i)
运行结果:
layer = int(input("请输入层数:"))
while layer & 1 == 0:
layer = int(input("层数必须是奇数层!"))
for i in range(1, layer//2 + 2):
print(" "* (layer - i), end="")
print("*"* (2*i - 1))
for i in range(layer//2, 0, -1):
print(" "* (layer - i), end="")
print("*"* (2*i - 1))
layer = int(input("请输入层数:"))
while layer & 1 == 0:
layer = int(input("层数必须是奇数层!"))
for i in range(1, layer//2 + 2):
print(" "* (layer - i), end="")
for j in range(1, 2*i):
if j == 1 or j == 2*i - 1:
print("*", end="")
else:
print(" ", end="")
print()
for i in range(layer//2, 0, -1):
print(" "* (layer - i), end="")
for j in range(1, 2*i):
if j == 1 or j == 2*i - 1:
print("*", end="")
else:
print(" ", end="")
print()
layer = int(input("请输入层数:"))
while layer & 1 == 0:
layer = int(input("层数必须是奇数层!"))
for i in range(1, layer//2 + 2):
print(" "* (layer - i), end="")
for j in range(1, 2*i):
if j == 1 or j == 2*i - 1 or j == i or i == layer//2 + 1:
print("*", end="")
else:
print(" ", end="")
print()
for i in range(layer//2, 0, -1):
print(" "* (layer - i), end="")
for j in range(1, 2*i):
if j == 1 or j == 2*i - 1 or j == i:
print("*", end="")
else:
print(" ", end="")
print()