im supposed to create a multiplication table in python but while i was creating it the labels (top and left) are just showing up as zeros. ?

i need it to have 0 1 2 3..up to n(user input value) for both top and left.

but instead it shows up as just 0 on top and 00000 on the left side. does anyone know how to fix this?

n = int(input("Please indicate how many rows you would like in the multiplication table (between 1 and 15):"))

i = 0

if (n < 1) or (n > 15):

    n = int(input("Please indicate how many rows you would like in the multiplication table (between 1 and 15):"))

if not (n < 1) or (n > 15):

    while i < (n + 1):

        j = 0

        while j <= i:

            if i == 0 and j == 0:

                print("x", end=" ")

                if i > 0 and j == 0:

                    print(i)

                if j > 0 and i == 0:

                        print(j, end=" ")

            if i >= 0 and j >= 0:

                print((i * j), end=" ")

            j += 1

        i += 1

        print()

Attachment image

2 Answers

Relevance
  • EddieJ
    Lv 7
    2 months ago
    Favorite Answer

    The short answer is:

    If j is zero, then i * j is zero

    Are you required to use <while> loops, or can you use <for> loops?

    n = 9999

    while (n < 1) or (n > 15):

        n = int (input ("Please indicate how many rows you would like in the multiplication table (between 1 and 15):"))

    for i in range (1, n+1):

        print (i, end=" ")

        for j in range (1, n+1):

            if j<=i: print (i*j, end=" ")

        print ()

  • 2 months ago

    The normal way to get labels on a table like this is to have

        1. an extra loop before the main loop to print column labels, and

        2. a print() call inside the outer loop, just before the inner loop, to print a row label.

    You use a loop to print column labels because there are a variable number of columns to be labeled.

    It looks like your numbers can go up to 15*15 = 225, so your table entries can require from 1 to 3 characters each.  It doesn't seem to me that there's any good reason for column labels if the columns aren't going to line up; but maybe that's a change you'll make in a later assignment.

    For now, you can just get column labels (part 1) with:

        print('x', end=' ')

        for y in range(0, n+1):

            print(y, end=' ')

    ...or write the while loop equivalent of that. Then add a print(i, end=' ') before the inner while loop.

    After that, you can throw away the if/then logic inside that inner loop.  All you need is the print(i*j, end=' ') statement, and the j = j + 1 statement. 

        j = 0

        while i <= i:

            print(i*j, sep=' ')

            j = j + 1

Still have questions? Get your answers by asking now.