Python 乘法 table 仅使用 while 循环

Python multiplication table with while loops only

我的任务是创建一个看起来像 this 的乘法 table,要求用户输入 1 到 9 之间的两个数字。(在图片中,用户输入 "rows=3" "col=5").

我无法正确排列我的顶行,这是一种让我的代码更好的方法吗? "better" 我的意思是只用 2 个 while 循环来完成整个事情?

编辑:我忘了只提到 WHILE 循环,而不是 "for"。

row=int(input("number of rows:"))
col=int(input("number of cols:"))
x=1
m=1
amount=col
while amount>0:
    print("%5d"%m, end="")
    m=m+1
    amount-=1
print()
while x<(row+1):
    y=1
    print(x, end="")
    while y<(col+1):
        print("%4d"%(x*y), end="")
        y=y+1
    print("\n")
    x=x+1

就像@Stewart_R在评论中提到的那样,很难说出你在寻找什么——但是打印乘法table的更简洁的方法看起来像:

row,col = 3,5  # Test case

style = "{:3d}"

print "   ",
for j in range(1, col+1):
    print style.format(j),
print
for i in range(1, row+1):
    print style.format(i),
    for j in range(1,col+1):
        print style.format(i*j),
    print

给出:

      1   2   3   4   5
  1   1   2   3   4   5
  2   2   4   6   8  10
  3   3   6   9  12  15

另一种方式:

for i in range(row+1):
    for j in range(col+1):
        print('{:4d}'.format(i*j if i*j>0 else i+j) if i+j>0 else '{:4s}'.format(''),end='')  
    print()

Juste 管理循环中心的所有 table。你也可以只有一个带有 while i*j <=row*col 的循环,如果 better 是循环的最小值。但是for循环是解决这个问题的最佳方案。

row,col=3,5
i=0
while i <= row :
    j=0
    while j <= col:
        if i+j==0 : print('{:4s}'.format(''),end='') #corner
        elif i*j==0 : print('{:4d}'.format(i+j),end='') # border
        else : print('{:4d}'.format(i*j),end='') # table
        j=j+1   
    print()
    i=i+1
i=0
num=int(input("enter the table number=")
limit=int(input("enter the limit=")
while(i<=limit):
     result= num * i
     print( num ,"x",i,"=",result)
     i=i+1
input("press enter to exit")

如果你想要任何table 运行 这个代码(Python 代码)

i=1
x=int(input("table() "))
while i<=10:
   print(i*x)
   i=i+1

例如,想要 12 的 table 输出 table(12) 12 24 36 48岁 60 72 84 96 108 120