2012-09-26 48 views
-1

我正在python中使用while循环构建乘法表。虽然数字排列齐整,但输出很奇怪。表格完成情况良好,但看起来很难看。我怎样才能拉直最后三列?我会张贴输出的照片,但我是一个新用户,它不会让我。python乘法表错误

width = int(input("Please enter the width of the table:")) 
def print_times_table(width): 

    row = 0 
    col = 0 
    width += 1 
    spaces = ' ' 

    while row < width: 
     col = 0 
     while col < width: 

      print(row*col, spaces, end="") 
      col += 1 
     print("\n", end='') 
     row +=1 

print_times_table(width) 

输出:http://i.stack.imgur.com/C9AzE.jpg

+1

如果这是作业,你应该这么说... – Triptych

回答

1

首先,你不需要的图片;你应该能够仅仅通过缩进四个空格(或使用{}图标),显示输出文本:

Please enter the width of the table:4 
0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 
0 4 8 12 16 

的问题是,你假设每个数字将是相同的宽度。这可以达到3x3,因为一切都是一个字符宽度,但对于5x5,一些数字是一个字符,一些是两个(当然,它在10x10时变得更糟)。

修复此问题的简单方法是将强制为,每个单元的宽度必须相同。

首先,你必须计算你需要的最大尺寸。但这很简单:它的尺寸为width*width

接下来,你必须知道如何强制数字用尽许多字符。 Python有几种方法可以做到这一点。我将演示如何使用老式的字段说明符来完成它,但是您应该研究如何将其转换为新式的格式字符串。 (如果这是家庭作业,那么有人教你Python 3可能会因为使用旧式的fieldspec而给你打分,如果只是为了你自己的自我教育,那么有必要弄清楚如何做到这一点。)或者,你也可以应该看看如何将其转换为使用可变宽度格式规范('%*d'),而不是构建一个静态的'%4d'规范。 (nneonneo的答案应该给一个线索了这一点。)

width = int(input("Please enter the width of the table:")) 
def print_times_table(width): 

    row = 0 
    col = 0  
    fieldspec = '%' + str(len(str(width * width))) + 'd' 
    width += 1 

    while row < width: 
     col = 0 
     while col < width: 

      print(fieldspec % (row*col,), ' ', end="") 
      col += 1 
     print("\n", end='') 
     row +=1 

print_times_table(width) 

现在,您可以:

Please enter the width of the table:4 
0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 
0 4 8 12 16 
+0

很棒的细节!我认为如果你使用了一个可变宽度的字段说明符,就像在其他答案中一样,这将会更加清晰。 –

+0

@SamMussmann:其实,这对读者来说是另一个很好的“练习”。我会编辑答案。 – abarnert

0

使用可变宽度的字段说明:

print('%*d' % (8, row*col), end='') 

这会自动添加足够的填充来填写数字到(这里)8个空格。您也可以将该间距参数作为参数传递。

print('{:{width}}'.format(row*col, width=8), end='') 
0

为什么不使用你的变量combonation与.ljust:

要使用新的样式格式的语法使用可变宽度?像这样:

width = int(13) 
def table(width): 

row = 1 
col = 1 
width += 1 
spaces = ' ' 

while row < width: 
    col = 1 
    while col < width: 
     print(str(row*col).rjust(5, ' '), end="") 
     col += 1 
    print("\n", end='') 
    row +=1 

table(width) 

它的工作原理完全一样(你可以使用任何号码,你想,无所谓了),只是相应地调整取决于你的数字是如何越来越大...