Properly formatted multiplication table

前端 未结 5 1507
青春惊慌失措
青春惊慌失措 2021-02-15 11:11

How would I make a multiplication table that\'s organized into a neat table? My current code is:

n=int(input(\'Please enter a positive integer between 1 and 15:          


        
5条回答
  •  被撕碎了的回忆
    2021-02-15 11:29

    Quick way (Probably too much horizontal space though):

    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()
    

    Better way:

    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)))
    

    And using f-strings (Python3.6+)

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

提交回复
热议问题