Printing a multiplication table with nested loops?

Question:

I’m having a really hard time trying to figure out this exercise.

Print the 2-dimensional list mult_table by row and column. Hint: Use nested loops. Sample output for the given program:

1 | 2 | 3
2 | 4 | 6
3 | 6 | 9

This is the code that I have so far

mult_table = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9]
]

for row in mult_table:
    for num in row:
        print(num,' | ',end='|')
    print()

What I get is this

1 ||2 ||3 ||
2 ||4 ||6 ||
3 ||6 ||9 ||

I have no idea what I’m doing wrong! I have also tried to do end=’ ‘ but that still leaves a space and | at the end of each row. Please help. I am using Python 3 btw.

Asked By: this.R.A

||

Answers:

You’re overthinking this. One loop should be enough here. You can unpack the inner lists and specify a sep parameter.

for m in mult_table:
     print(*m, sep=' | ')

1 | 2 | 3
2 | 4 | 6
3 | 6 | 9

If you want two loops, you will need to programmatically control the separators and the end characters to be printed out at each inner loop iteration.

for i in mult_table:
    for c, j in enumerate(i):
        sep = '|' if c < len(i) - 1 else ''
        end = ' ' if c < len(i) - 1 else 'n' 
        print(j, sep, end=end)

1 | 2 | 3 
2 | 4 | 6 
3 | 6 | 9 
Answered By: cs95

Use join with map:

mult_table = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9]
]

for row in mult_table:
    print(" | ".join(map(str, row)))

Output:

1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
Answered By: eyllanesc

Low-Level: Your code shows two '|' after each number because that’s what you’re telling it to do (one of them is passed to print() right after num, and one of them is added by the use of end='|', which tells print() to add a '|' at the end of the printed string).

Using end='' avoids the second '|', but you still end up with a pipe character at the end of each row from the print() call.

To get '|' between items, but not at the end of the row, you need to handle the last item in each row specially (or, better use " | ".join(row) to add the separators automatically).

High-Level: You’re likely not solving this problem the way it was intended to be solved.

Your answer hard-codes the multiplication table, but you could be generating it as part of the loop, like:

# Store the size of the table here 
# So it's easy to change later
maximum = 3
# Make a row for each y value in [1, maximum]
for y in range(1, maximum + 1):
    # Print all x * y except the last one, with a separator afterwards and no newline
    for x in range(1, maximum):
        print(x * y, end=' | ')
    # Print the last product, without a separator, and with a newline
    print(y * maximum)

This solves the specific problem given, but we can now change the value of “maximum” to also generate a square multiplication table of any size, and we don’t have to worry about errors in our multiplication table.

Answered By: Ollin Boer Bohan
for row in mult_table:
    line = 0
    for num in row:
        if line < len(mult_table) - 1:
            print(num, '| ', end = '')
            line += 1
        else:
            print(num)

This will iterate through each of the rows step by step checking through the if statement to see if it has reached the end of the row, printing the | between each num in the row until the end which will simply print the num followed by a return to next line.

Placing the line = 0 inside the first loop is essential as putting it outside the first loop will cause line to already meet the else requirement of the if statement. With it inside the initial loop, each iteration causes line to reset to 0, which allows the nested if to function properly.

Answered By: William Thatcher
   row_length = len(mult_table[0]) #Gets length of the first row.

   for row_index, row in enumerate(mult_table): #Loops trough each row.
       count = 1 #Sets count
       cell_index = 0 #Sets cell index count
       while count != row_length: #Checks if end of the row
           print(f'{mult_table[row_index][cell_index]} | ', end='') #Print
           count += 1 #Count increase
           cell_index += 1 #Count increase
       else:
           print(f'{mult_table[row_index][cell_index]}') #Print
           count += 1 #Count increase
           cell_index += 1 #Count increase

Here is a solution using nested loops and without using .join.

Answered By: Spamlite

This worked for me:

mult_table = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9]
]
row_num = 0


for row in mult_table:
    i = 0
    for cell in row:
       
        if i < len(mult_table) -1:
            print(cell,'| ', end='')
            i +=1
        else: print(cell)
'''
Answered By: Andrew Skinner

Here is a solution I came up with. I haven’t learned some of the things I see in the examples above, so I just made what I have learned work. My first post, I’m sure if it is ever seen I will learn etiquette and format etc… One problem I feel like exists, is the rowlen variable. I want it to be the amount of elements in the row, not the amount of nested list elements in the mult_table list.

# existing code
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]

# my code
#   |
#  |/
#   V

x = '| '
rowlen = len(mult_table) - 1

# print(x, rowlen) # testing values

for row in mult_table:
    for cell in row[0:rowlen]:
        print(cell, '{}'.format(x), end='')
    print(row[rowlen])
Answered By: icodeunot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.