Printing a table in Python

空扰寡人 提交于 2021-02-08 05:14:41

问题


I have an assignment to create a 10 by 10 table in Python and I'm using the end "\t" within my print function to prevent it from creating a new line. But, I need it to start a new line after of course 10 characters. How can I make it do that? Here's my code:

product = 0
for x in range(1,11):
    for y in range(1,11):
        product = x * y
        print(product, end="\t")

I need it to look something like this:

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

回答1:


This is using alignement options from the format method.

product = 0
for x in range(1,11):
    for y in range(1,11):
        product = x * y
        print('{:<4}'.format(product), end='')
    print()

Reference: Format specification mini-language




回答2:


I think all you would need to add to get what you want is to print a new line in your inner loop like so:

product = 0
for x in range(1,11):
    print()
    for y in range(1,11):
        product = x * y
        print(product, end="\t")

On the third line it'll start a new line after 10. The output will look like this: 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




回答3:


For fun, this can be done as a one liner with a bit of list comprehension and the join method

print('\n'.join(['\t'.join([str(x*y) for x in range(1,11)]) for y in range(1,11)]))


来源:https://stackoverflow.com/questions/43244717/printing-a-table-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!