Python - 围绕总和的动态括号

时间:2017-09-24 18:54:49

标签: python

我正在处理一个程序,它接受一个数字并打印其时间表,并用括号括起来,这一切都正常,直到答案进入两位数

CODE:

number = int(input("Input a number: "))

length_of_sum = len(str(number))
longest = len(str(number*10))
length_of_sum = length_of_sum + 12 + longest
print('+-' + '-'*(length_of_sum) + '-+')
i = 1
for i in range(10):
    print('| ',number, " X ", i, " = ",number*i, '|')
    i = i + 1

print('+-' + '-'*(length_of_sum) + '-+')

输出:

Input a number:3
+-----------------+
|  3  X  0  =  0 |
|  3  X  1  =  3 |
|  3  X  2  =  6 |
|  3  X  3  =  9 |
|  3  X  4  =  12 |
|  3  X  5  =  15 |
|  3  X  6  =  18 |
|  3  X  7  =  21 |
|  3  X  8  =  24 |
|  3  X  9  =  27 |
+-----------------+

正如你所看到的一切正常但边界太大了,或者我应该 说边界开始太小。

(注意:你能否相对简单地回答这个问题,因为我在python方面还不是很好。

1 个答案:

答案 0 :(得分:1)

您可以将所有数字格式化为n位数,其中n是number*10中的位数:

number = int(input("Input a number: "))

length_of_sum = len(str(number))
longest = len(str(number*10))
length_of_sum = length_of_sum + 12 + longest
print('+-' + '-'*(length_of_sum) + '-+')
i = 1
m = str(longest)+'d'
for i in range(10):
    print('| ',number, " X ", i, " = ",format(number*i, m), '|')
    i = i + 1

print('+-' + '-'*(length_of_sum) + '-+')

运行1:

Input a number:  3
+-----------------+
|  3  X  0  =   0 |
|  3  X  1  =   3 |
|  3  X  2  =   6 |
|  3  X  3  =   9 |
|  3  X  4  =  12 |
|  3  X  5  =  15 |
|  3  X  6  =  18 |
|  3  X  7  =  21 |
|  3  X  8  =  24 |
|  3  X  9  =  27 |
+-----------------+

运行2:

Input a number:  18
+-------------------+
|  18  X  0  =    0 |
|  18  X  1  =   18 |
|  18  X  2  =   36 |
|  18  X  3  =   54 |
|  18  X  4  =   72 |
|  18  X  5  =   90 |
|  18  X  6  =  108 |
|  18  X  7  =  126 |
|  18  X  8  =  144 |
|  18  X  9  =  162 |
+-------------------+