#如果不加条件控制,打印的就是乘法矩阵
for i in range(1, 10):
s = '' # 每次将s清空
for j in range(1, 10):
s += str(j) + '*' + str(i) + '=' + str(i*j) + ' '
print(s)
# 过滤掉不符合条件的部分,打印出正常的99乘法表
for i in range(1, 10):
s = ''
for j in range(1, 10):
if j < i+1:
s += str(j) + '*' + str(i) + '=' + str(i*j) + ' '
print(s)
# range范围改进版,既然j的范围受i控制,就以此简化j的range
for i in range(1, 10):
s = '' # 每次将s清空
for j in range(1, i+1):
s += str(j) + '*' + str(i) + '=' + str(i*j) + ' '
print(s)
# print函数改进版
for i in range(1, 10):
for j in range(1, i+1):
print(str(j) + '*' + str(i) + '='+str(i*j), end='\t')
print()
# print函数改进版2
for i in range(1, 10):
for j in range(1, i+1):
print(j, '*', i, '=', i*j, sep='', end='\t')
print()
# format函数改进版
for i in range(1, 10):
for j in range(1, i+1):
print('{}*{}={}\t'.format(i, j, i*j), end='')
print()
# format函数改进版2
for i in range(1, 10):
for j in range(1, i+1):
print('{}*{}={:<2}'.format(i, j, i*j), sep='', end='\t')
print()
# 添加条件,通过控制输出的占位符强制对齐
for i in range(1, 10):
for j in range(1, i+1):
mult = i * j
if j > 1 and mult < 10:
mult = str(mult) + ' '
else:
mult = str(mult)
print(str(j)+'*'+str(i)+'=' + mult, end=' ')
print()
# 索引format改进版,通过<>符号来控制居左或居右对齐
for i in range(1, 10):
line = ''
for j in range(1, i+1):
# line += '{0}*{1}={2:<2}\t'.format(j, i, i*j)
line += '{}*{}={:<2}\t'.format(j, i, i * j)
print(line)
如果要打印如下倒三角的乘法表
根据上面的打印稍作修改
同理过滤掉不符合条件的,只用加一个判断,再对输出的内容进行控制,大功告成
for i in range(1, 10):
for j in range(1, 10):
if j < i:
print('', sep='', end='\t')
else:
print('{}*{}={}'.format(i, j, i*j), sep='', end='\t')
print()
改进版,通过字符拼接和缩进控制对齐
for i in range(1, 10):
s = ''
for j in range(i, 10):
s += '{}*{}={:<{}} '.format(i, j, i*j, 2 if j < 4 else 3)
print('{:>70}'.format(s))