格式正确的乘法口诀表

问题描述 投票:0回答:20

如何制作一个整齐的乘法表?我当前的代码是:

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col)
    print()

这正确地将所有内容相乘,但以列表形式呈现。我知道我需要将其嵌套并适当放置空间,但我不确定它会去哪里?

python string algorithm python-3.x formatting
20个回答
18
投票

快速方法(可能水平空间太大):

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col, end="\t")
    print()

更好的方法:

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    print(*("{:3}".format(row*col) for col in range(1, n+1)))

并使用 f 字符串(Python3.6+)

for row in range(1, n + 1):
    print(*(f"{row*col:3}" for col in range(1, n + 1)))

6
投票

Gnibbler 的方法相当优雅。我首先使用 range 函数并利用 step 参数来构建整数列表的方法。

对于 n = 12

import pprint
n = 12
m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
pprint.pprint(m)
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60],
 [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72],
 [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84],
 [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96],
 [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108],
 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
 [11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132],
 [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144]]

现在我们有了一个我们想要的形式的整数列表, 我们应该将它们转换为宽度右对齐的字符串 比列表列表中最大整数(最后一个整数)大的一个, 使用 fillchar 的默认参数

' '

max_width = len(str(m[-1][-1])) + 1
for i in m:
    i = [str(j).rjust(max_width) for j in i]
    print(''.join(i))

   1   2   3   4   5   6   7   8   9  10  11  12
   2   4   6   8  10  12  14  16  18  20  22  24
   3   6   9  12  15  18  21  24  27  30  33  36
   4   8  12  16  20  24  28  32  36  40  44  48
   5  10  15  20  25  30  35  40  45  50  55  60
   6  12  18  24  30  36  42  48  54  60  66  72
   7  14  21  28  35  42  49  56  63  70  77  84
   8  16  24  32  40  48  56  64  72  80  88  96
   9  18  27  36  45  54  63  72  81  90  99 108
  10  20  30  40  50  60  70  80  90 100 110 120
  11  22  33  44  55  66  77  88  99 110 121 132
  12  24  36  48  60  72  84  96 108 120 132 144

并展示不同尺寸间距的弹性,例如

n = 9

n=9
m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
for i in m:
    i = [str(j).rjust(len(str(m[-1][-1]))+1) for j in i]
    print(''.join(i))

  1  2  3  4  5  6  7  8  9
  2  4  6  8 10 12 14 16 18
  3  6  9 12 15 18 21 24 27
  4  8 12 16 20 24 28 32 36
  5 10 15 20 25 30 35 40 45
  6 12 18 24 30 36 42 48 54
  7 14 21 28 35 42 49 56 63
  8 16 24 32 40 48 56 64 72
  9 18 27 36 45 54 63 72 81

4
投票
for i in range(1, 10) :
    for j in range(1, 10):
        print(repr(i*j).rjust(4),end=" ")
print()
print()

输出:

  1    2    3    4    5    6    7    8    9 

  2    4    6    8   10   12   14   16   18 

  3    6    9   12   15   18   21   24   27    

  4    8   12   16   20   24   28   32   36

  5   10   15   20   25   30   35   40   45 

  6   12   18   24   30   36   42   48   54 

  7   14   21   28   35   42   49   56   63 

  8   16   24   32   40   48   56   64   72 

  9   18   27   36   45   54   63   72   81 

或者这个

for i in range(1, 11):
    for j in range(1, 11):
        print(("{:6d}".format(i * j,)), end='')
print()

结果是:

 1     2     3     4     5     6     7     8     9    10
 2     4     6     8    10    12    14    16    18    20
 3     6     9    12    15    18    21    24    27    30
 4     8    12    16    20    24    28    32    36    40
 5    10    15    20    25    30    35    40    45    50
 6    12    18    24    30    36    42    48    54    60
 7    14    21    28    35    42    49    56    63    70
 8    16    24    32    40    48    56    64    72    80
 9    18    27    36    45    54    63    72    81    90
10    20    30    40    50    60    70    80    90   100

2
投票

创建算术表要简单得多,但我认为我应该发布我的答案,尽管这个问题有很多答案,因为没有人谈论表的限制。

将用户输入作为整数

num = int(raw_input("Enter your number"))

设置表的限制,我们希望在多大程度上计算所需数量的表

lim = int(raw_input("Enter limit of table"))

从索引1开始迭代计算

在此,我利用格式切片来调整数字之间的空白,即 {:2} 用于两个空间调整。

for b in range(1, lim+1):
    print'{:2} * {:2} = {:2}'.format(a, b, a*b)

最终代码:

num = int(raw_input("Enter your number"))
lim = int(raw_input("Enter limit of table"))
for b in range(1, lim+1):
    print'{:2} * {:2} = {:2}'.format(a, b, a*b)

输出:

Enter your number 2
Enter limit of table 20
 2 *  1 =  2
 2 *  2 =  4
 2 *  3 =  6
 2 *  4 =  8
 2 *  5 = 10
 2 *  6 = 12
 2 *  7 = 14
 2 *  8 = 16
 2 *  9 = 18
 2 * 10 = 20
 2 * 11 = 22
 2 * 12 = 24
 2 * 13 = 26
 2 * 14 = 28
 2 * 15 = 30
 2 * 16 = 32
 2 * 17 = 34
 2 * 18 = 36
 2 * 19 = 38
 2 * 20 = 40

1
投票

或者你可以这样做(不像其他方法那么简单,但它有效):

def main():

    rows = int(input("Enter the number of rows that you would like to create a multiplication table for: "))
    counter = 0
    multiplicationTable(rows,counter)

def multiplicationTable(rows,counter):

    size = rows + 1

    for i in range (1,size):
        for nums in range (1,size):
            value = i*nums
            print(value,sep=' ',end="\t")
            counter += 1
            if counter%rows == 0:
                print()
            else:
                counter
main()

1
投票

这个看起来很整洁:

   print '\t\t\t======================================='
   print("\t\t\t\tMultiplication Tables")
   print '\t\t\t=======================================\n'
   for i in range(1,11):
       print '\t', i,
   print
   print("___________________________________________________________________________________________________________________")

   for j in range(1,11):
       print("\n")
       print j, '|',
       for k in range(1,11):
           print '\t', j * k,
   print("\n")

1
投票
for x in range(1, 11):
        for y in range(1, 11):
            z = x * y
            print(z, end="\t")
        print() #creates the space after the loop

上面的代码将产生以下结果:


0
投票

对于此打印如下

 print "%d X %d"%(row, col)

它将打印为 2 X 3。


0
投票

您可以通过将其中一个循环放入

print
调用中来更轻松地实现您想要的效果。

n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1, n+1):
    print('\t'.join(str(row * col) for col in range(1, n+1)))

这将创建一个生成器,生成

row*1
row*2
、...
row*n
的字符串值,用制表符连接每个值,并将生成的字符串传递给
print()


0
投票

你的问题是 print 添加了换行符,而你不想要所有这些换行符。

一种方法是为每一行构建一个字符串,然后在一个打印语句中打印出整行。

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    s = ''
    for col in range(1,n+1):
        s += '{:3} '.format(row * col)
    print(s)

神奇之处在于

'{:3} '.format
位。这很棘手,所以这里有一个教程:http://ebeab.com/2012/10/10/python-string-format/

这是正在运行的代码:

Please enter a positive integer between 1 and 15: 4
  1   2   3   4 
  2   4   6   8 
  3   6   9  12 
  4   8  12  16 

0
投票
n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col, "\t",end = "")      
    print()

#the "\t" adds a tab each time, and the end = "" prints your string horizontally.

0
投票

这是我组织输出的方式:

for row in range(1, 11):
    for col in range(1, 11):
        num = row * col
        if num < 10: blank = '  '       # 2 blanks
        else:
            if num < 100: blank  = ' '  # 1 blank
        print(blank, num, end = '')     # Empty string
    print()                             # Start a new line

0
投票

这对于标准乘法表非常有效,对于初学者来说很容易用编码来解释:

x = 12
y = 12
print ' ',
for fact in range(1, x+1):
    str(fact).rjust(6),
for fact in range(1, y+1):
    print
    print fact,
    for i in range(1,y+1):
        product = i * fact
        print str(product).rjust(5),
    print

0
投票

乘法口诀表有很多答案。这里我通过调用函数来完成。随时改进。

    num = int(input('Please enter time tables for printing: '))
    upperLimit = int(input('Please enter upper limit: '))

    def printTable(num, upperLimit):   
        for i in range(0, upperLimit+1):
            print(num, 'x', i, '=', num * i)

    def main():
        printTable(num, upperLimit)

    main()    

0
投票

这对我来说很有效:

num, b, c, count = int(input('Enter a number')), '  ', '   ', 0
for i in range(1, num+1):
    if i > 9:
        b = b + str(i) + '   '
        c = c + str(i) + '|'
    else:
        b = b + str(i) + '    '
        c = c + str(i) + ' |'
    for a in range(1, num+1):
        d = str(a*i)
        for letter in d:
            count += 1
        c = c + str(a*i) + ' '*(5-count)
        count = 0
    c = c + '\n   '
print((' ')*4 + b)
print((' ')*6 + ('-'+ '    ')*num)
print(c)

它可以乘以 99。

输入数字12时输出:

      1    2    3    4    5    6    7    8    9    10   11   12   
      -    -    -    -    -    -    -    -    -    -    -    -    
   1 |1    2    3    4    5    6    7    8    9    10   11   12   
   2 |2    4    6    8    10   12   14   16   18   20   22   24   
   3 |3    6    9    12   15   18   21   24   27   30   33   36   
   4 |4    8    12   16   20   24   28   32   36   40   44   48   
   5 |5    10   15   20   25   30   35   40   45   50   55   60   
   6 |6    12   18   24   30   36   42   48   54   60   66   72   
   7 |7    14   21   28   35   42   49   56   63   70   77   84   
   8 |8    16   24   32   40   48   56   64   72   80   88   96   
   9 |9    18   27   36   45   54   63   72   81   90   99   108  
   10|10   20   30   40   50   60   70   80   90   100  110  120  
   11|11   22   33   44   55   66   77   88   99   110  121  132  
   12|12   24   36   48   60   72   84   96   108  120  132  144  

0
投票
table = int(input("Enter a Positive Number: "))
for i in range(1,11):
    print(table, 'X', i, '=', table*i)
print("See you later, Alligator!")

0
投票
for i in range(2,11):
    print("=============")
    print("~table of {}~".format(i))
    print("=============")
    for j in range(1,11):
        print("{} X {} = {}".format(i, j, i*j))
print("=============")

0
投票

使用此代码。它比这里的任何答案都好得多。我必须在学校这样做,在花了大约 4 个小时之后,我可以告诉你,它工作得非常完美。

def returnValue(int1, int2):
    return int1*int2

startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")

int1 = int(startingPoint)
int2 = int(endingPoint)

spacing = "\t"

print("\n\n\n")
if int1 == int2:
    print("Your integers cannot be the same number. Try again. ")
    

if int1 > int2:
    print("The second number you entered has to be greater than the first. Try again. ")


for column in range(int1, int2+1, 1):  #list through the rows(top to bottom)
    
    if column == int1:
            for y in range(int1-1,int2+1):
                if y == int1-1:
                    print("", end=" \t") 
                    
                else: 
                    individualSpacing = len(str(returnValue(column, y)))
                    print(y, " ", end=" \t")
            print()
            
    print(column, end=spacing)

    
    for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
        #print("second range val: {:}".format(row))
        
            individualMultiple = returnValue(row, column)
            print(individualMultiple, " ", end = "\t")
        
    print("")

输出: Result after entering 5 and 8

或者, Result after entering 40 and 45


0
投票

好的,这是我的 2 美分。它使用 Python3 f 字符串根据表格大小的平方(m*m)调整列宽:

m = int(input("Multiplcation table to?: "))
w = len(str(m*m)) # Column size
for i in range(1,m+1):
    print(*(f"{j*i:{w}}" for j in range(1,m+1)))

输出:

$ python m_table.py 
Multiplcation table to?: 3
1 2 3
2 4 6
3 6 9

和12

$ python m_table.py 
Multiplcation table to?: 12
  1   2   3   4   5   6   7   8   9  10  11  12
  2   4   6   8  10  12  14  16  18  20  22  24
  3   6   9  12  15  18  21  24  27  30  33  36
  4   8  12  16  20  24  28  32  36  40  44  48
  5  10  15  20  25  30  35  40  45  50  55  60
  6  12  18  24  30  36  42  48  54  60  66  72
  7  14  21  28  35  42  49  56  63  70  77  84
  8  16  24  32  40  48  56  64  72  80  88  96
  9  18  27  36  45  54  63  72  81  90  99 108
 10  20  30  40  50  60  70  80  90 100 110 120
 11  22  33  44  55  66  77  88  99 110 121 132
 12  24  36  48  60  72  84  96 108 120 132 144

-3
投票

还有:

table = 12 
for i in range(1,11): 
    print(i*table)
© www.soinside.com 2019 - 2024. All rights reserved.