Skip to content
Advertisement

Is there a way to add a 0 in the corner of a multiplication table

This is my code:

def multiply(end):
    pro = ""
    for i in range(end + 1):
        for j in range(end + 1):
            pro += str(i * j) + "t"
        pro += "n"
    return pro

When I run my code it returns when I call the function multiply(4):

0   0   0   0   0   
0   1   2   3   4   
0   2   4   6   8   
0   3   6   9   12  
0   4   8   12  16

I want it to return as:

0   1   2   3   4   
1   1   2   3   4   
2   2   4   6   8   
3   3   6   9   12  
4   4   8   12  16

What do I have to change and I also need to return the table instead of printing the table.

Advertisement

Answer

you need to add a few checks to your function but this should work –

def multiply(end):
    pro = ""
    for i in range(0,end + 1):
        for j in range(0,end + 1):
            if i != 0 and j != 0:
                pro += str(i * j) + "t"
            else:
                pro += str(max(j,i)) + "t"
        pro += "n"
    return pro

with this multuply(4) has an output of –

0       1       2       3       4
1       1       2       3       4
2       2       4       6       8
3       3       6       9       12
4       4       8       12      16
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement