pythonfunctionfor-loop

Python multiplication table school exercise


I have a school exercise, but I'm struggling to understand how to do the multiplication table. Could someone please help me?

Multiplication Tables

So depending on the number and columns_number the multiplication table has to be different.

I have tried to solve this this way:

number1 = 4
column1 = 3

for row in range(column1):
   for y in range(10):
       print("0"+str(number1)+" "+"x"+"0"+"")

But i dont know what to put in the print statement. Could someone please explain me how to solve this exercise


Solution

  • It will be easier to understand if you break it down into its component parts.

    First of all build a list of strings where each string represents a 'cell' in your multiplication table.

    Once you have that you can handle the output formatting.

    Something like this:

    def mtable(x, c):
        vlist = []
        for i in range(1, 10):
            vlist.append(f'{x:02d} x {i:02d} = {x*i:02d}')
        for i in range(0, 10, c):
            print('\t'.join(vlist[i:i+c]))
    
    mtable(4, 3)
    

    Output:

    04 x 01 = 04    04 x 02 = 08    04 x 03 = 12
    04 x 04 = 16    04 x 05 = 20    04 x 06 = 24
    04 x 07 = 28    04 x 08 = 32    04 x 09 = 36