乘法表python嵌套循环未打印完整表
这是到目前为止我的乘法表代码。对于如何继续完成这个问题,我有点困惑,基本上我需要能够以这种格式打印1到9之间任意数字的乘法表:乘法表python嵌套循环未打印完整表,python,Python,这是到目前为止我的乘法表代码。对于如何继续完成这个问题,我有点困惑,基本上我需要能够以这种格式打印1到9之间任意数字的乘法表: 1 2 3 4 5 -------------------------- 1| 1 2 3 4 5 2| 2 4 6 8 10 3| 3 6 9 12 15 4| 4 8 12 16 20 5| 5 10 15 20 25 x =
1 2 3 4 5
--------------------------
1| 1 2 3 4 5
2| 2 4 6 8 10
3| 3 6 9 12 15
4| 4 8 12 16 20
5| 5 10 15 20 25
x = int(input("enter a number 1-9: "))
output = ""
for x in range(1 ,x+1):
output +=str(x) +"|\t"
for y in range(1,x+1):
output += str(y * x) +"\t"
output +="\n"
print(output)
您正在替换循环中的
x
值,而应该为循环参数使用不同的名称:
output = ' '.join([f" {i}" for i in range(1, x+1)]) + "\n"
output += '---' * x + "\n"
for i in range(1, x+1):
output += str(i) + "| "
for y in range(1, x+1):
output += str(y * i) + " "
output += "\n"
循环变量应具有不同的名称,而不是
x
。x的值被循环值覆盖。您的代码应该如下所示
for i in range(1, x + 1):
output += str(i) + "| "
for y in range(1, x + 1):
output += str(y * i) + " "
output += "\n"
为了获得良好的输出,您还必须注意填充,并且在第一个循环中,您必须更改用于迭代的变量的名称:
x = int(input("enter a number 1-9: "))
sep = ' '
sep_len = len(sep)
output = ' ' + sep + sep.join(str(e).rjust(sep_len, ' ') for e in range(1, x + 1))
output += '\n' + '_' * len(output)
for i in range(1 , x + 1):
output += "\n" + str(i) + '|'
for y in range(1, x + 1):
output += sep + str(y * i).rjust(sep_len, ' ')
print(output)
输出(对于x=5):
当我这样做并说,输入3时,它打印出所有完美的东西,除了我需要的顶部部分,它是由--Hi Kamal分隔的顶层,我更新了我的答案来写顶层。不,使用
\t
,它在输出中打印\t
。这就是我跳过它的原因。
1 2 3 4 5
__________________________________________
1| 1 2 3 4 5
2| 2 4 6 8 10
3| 3 6 9 12 15
4| 4 8 12 16 20
5| 5 10 15 20 25