'Python multiplication table school exercise

I have a school exercise, but im struggling to understand how to do the multiplication table. Could someone please help me? enter image description here

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 1:[1]

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

Solution 2:[2]

You can try something like this,

def multiplication_table(num, columns):
  output = ""

  for i in range(1, 10):
    output += f"{num} x {i} = {str(num * i).zill(2)}"
    
    if i % columns == 0:
      output += "\n"
    else:
      output += "\t"

  return output

print(multiplication_table(8, 2))

Output -

8 x 1 = 08  8 x 2 = 16
8 x 3 = 24  8 x 4 = 32
8 x 5 = 40  8 x 6 = 48
8 x 7 = 56  8 x 8 = 64
8 x 9 = 72  

Solution 3:[3]

You need something to input numbers:

def get_number(text,rng):
    """Ask with 'text' until the given input is int()-able and 
    inside range 'rng'. Return the integer - present error and 
    loop if not an int input or outside of specified."""
    while True:
        try:
            t = input(text)
            n = int(t)
            if n in rng:
                return n
            print("Invalid number, use integer in", rng)
        except ValueError:
            print("Invalid number, use integer in", rng)

You need something to create the table - string concatenation is wasteful, so use lists instead and '--'.join("1","3"]) to joint them back into a string.

To format the numbers, use pythons Format Specification Mini-Language to right-align and pad numbers in strings:

def mult_table(num, times, cols):
    out = [[]]

    # calculate max width for spacing reasons
    maxw =len(str(num*times))
    for i in range(1, times+1):

        # add to last list inside out
        # format numbers right aligned '>' with leading '0' to 'maxw' digits
        out[-1].append( f"{num:>0{maxw}} x {i:>0{maxw}} = {num * i:>0{maxw}}")
        
        # if out's last list reached length you need a new line, add new []
        if len(out[-1])==cols:
            out.append([])

    # create the texts from your list of lists
    return '\n'.join('   '.join(e) for e in out)

Then you need to get some inputs:

n = get_number("What table? ", range(1,21))
t = get_number("Up to what multiplyer? ", range(1,51))
c = get_number("How many columns? ", range(1, n+1))

print(mult_table(n, t, c))

To get:

What table? 8
Up to what multiplyer? 12
How many columns? 3
08 x 01 = 08   08 x 02 = 16   08 x 03 = 24
08 x 04 = 32   08 x 05 = 40   08 x 06 = 48
08 x 07 = 56   08 x 08 = 64   08 x 09 = 72
08 x 10 = 80   08 x 11 = 88   08 x 12 = 96

What table? 13
Up to what multiplyer? 42
How many columns? 7
013 x 001 = 013   013 x 002 = 026   013 x 003 = 039   013 x 004 = 052   013 x 005 = 065   013 x 006 = 078   013 x 007 = 091
013 x 008 = 104   013 x 009 = 117   013 x 010 = 130   013 x 011 = 143   013 x 012 = 156   013 x 013 = 169   013 x 014 = 182
013 x 015 = 195   013 x 016 = 208   013 x 017 = 221   013 x 018 = 234   013 x 019 = 247   013 x 020 = 260   013 x 021 = 273
013 x 022 = 286   013 x 023 = 299   013 x 024 = 312   013 x 025 = 325   013 x 026 = 338   013 x 027 = 351   013 x 028 = 364
013 x 029 = 377   013 x 030 = 390   013 x 031 = 403   013 x 032 = 416   013 x 033 = 429   013 x 034 = 442   013 x 035 = 455
013 x 036 = 468   013 x 037 = 481   013 x 038 = 494   013 x 039 = 507   013 x 040 = 520   013 x 041 = 533   013 x 042 = 546

# handles bad input gracefully
What table? apple
Invalid number, use integer in range(1, 21)
What table? 42
Invalid number, use integer in range(1, 21)
What table?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Patrick Artner