Search code examples
pythonmultiplication

Python Nested For-loop Multiplication Table Must Have Exact Output of Teacher


Have a school project that I just can't seem to crack. I need to create a python multiplication table using for-loops and nested for loops. I have the code to create the table but the problem is that I have to copy the exact output that my teacher got when he made the program. His output:Output of the program. My current code looks like this:

n = 12

print("*\t|", end = "\t")

for i in range(1, 13):
    print(i, end = "\t")

print()

for i in range(1, 112):
    print("=", end = "")

print()

for i in range(1, 13, 1):
    print(i, "\t|")

for row in range(1, n + 1):
    for col in range(1, n+1):
        print(row * col, end = "\t")
    print()

Any help would be much appreciated (sorry for any bad formatting this is my first post!)


Solution

  • You need to merge the code for the i loop and the row loop:

    for row in range(1, n + 1):
        print(row, "\t|", end = "\t")
        for col in range(1, n+1):
            print(row * col, end = "\t")
        print()
    

    Also, you might replace your 13 everywhere with n+1 for consistency, if you haven't already done that.