Multiplication table for double digit numbers using nested loops in Python

24,678

If you are using Python 2.x, print is a statement, so you need to make sure that the line doesn't end after printing the current line. {:2d} in the format function makes sure that you have always have space for two digits. If you prefer 0 instead of spaces you can use {:02d}.

for i in range(1, 10):
    print "i =", i, ":",                   # Note the comma at the end
    for j in range(1, 10):
        print "{:2d}".format(i * j),       # Note the comma at the end
    print

Output

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

Small change in the print, can make it work in Python 3.x, as well. Remember print is a function in Python 3.x

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

Note: You can read more about the various string formatting options, in the Format Specification Mini-Language section of the Python docs.

Share:
24,678
Admin
Author by

Admin

Updated on February 01, 2020

Comments

  • Admin
    Admin about 4 years

    I am trying to learn nested loops so I want to make a simple multiplication table, could you please help me improve my code?

    for i in range(1,10):
        print("i =", i, ":")
        for j in range(1, 10):
            print (i*j)
    

    My program looks very messy when I run it, how can I align the results in something like a matrix/table to make it easier to read?

  • Admin
    Admin about 10 years
    Thank you for the answer, that seems fine but I wanted it to be a table, i.e. like a matrix or a chess board, for example, like this: study-skills-for-all-ages.com/image-files/…
  • Admin
    Admin about 10 years
    Thank you, that is what I wanted!
  • Admin
    Admin about 10 years
    Also, thank you very much for the reference, I was going to ask you where I can learn more about formatting.
  • thefourtheye
    thefourtheye about 10 years
    @user2357 Since you said you are learning, I thought it would help you :)