最近学习了python语言的循环结构,与其他语言不同,python语言的循环结构只有两种:一是 for in 结构,另一是 while结构,在Python中,只用这两种循环就可以实现所有循环结构的功能,相对来说对初学者来说非常友好。为了练习理解这两种循环结构,试着完成4种九九乘法表的制作,是哪4种?
算法并不复杂,普通九九乘法表需要套用两次循环,一层循环控制行,另一层循环来控制列,对于第2 ,4 种的形式的需要三层循环,多一层用来控制每行空格的数量,以下是具体代码:
#for 循环实现4种九九乘法表
for i in range(1,10):
for j in range(1,i + 1):
print('%d*%d=%2d ' % (j, i, j * i),end = '')
print()
for i in range(1,10):
for k in range(1,10 - i):
print('%s' % (' '),end = '')
for j in range(1,i + 1):
print('%d*%d=%2d ' % (j, i, j * i),end = '')
print()
for i in range(9,0,-1):
for j in range(1, i + 1):
print('%d*%d=%2d ' % (j, i, j * i),end = '')
print()
for i in range(9,0,-1):
for k in range(0,9 - i):
print('%s' % (' '),end = '')
for j in range(1, i + 1):
print('%d*%d=%2d ' % (j, i, j * i),end = '')
print()
#while 循环实现4种九九乘法表
i = 1
while i < 10:
j = 1
while j < i + 1:
print('%d*%d=%2d ' % (j, i, j * i),end = '')
j += 1
i += 1
print()
i = 1
while i < 10:
k = 1
while k < 10 - i:
print('%s' % (' '),end = '')
k += 1
j = 1
while j < i + 1:
print('%d*%d=%2d ' % (j, i, j * i),end = '')
j += 1
i += 1
print()
i = 9
while i > 0:
j = 1
while j < i + 1:
print('%d*%d=%2d ' % (j, i, j * i),end = '')
j += 1
i -= 1
print()
i = 9
while i > 0:
k = 0
while k < 9 - i:
print('%s' % (' '),end = '')
k += 1
j = 1
while j < i + 1:
print('%d*%d=%2d ' % (j, i, j * i),end = '')
j += 1
i -= 1
print()
help(range)
for i in range(0,10,2):
print(i)
这就实现了4种九九乘法表,思路不难,主要是用来练习学到的两种循环结构,学习编程有时很枯燥,试着给自己找一些有意思的东西做一做,并用代码去实现,那我们的编程能力一定会越来越强大!!
Python学习交流、资源共享群:563626388 QQ