Home > database >  Issue formatting a multiplication table in Python using nested loops
Issue formatting a multiplication table in Python using nested loops

Time:12-13

I've gotten everything formatted correctly, except for the top labels for the columns and the underline that goes underneath the column labels. I suspect the first for loop is incorrectly coded, but I can't figure out what I am doing wrong.

def main():

    print("This is a times-table.")

    n = int(input("Enter a number: "))
        
    for i in range(1,n 1):
        print(" {:3d}".format(i), end='')
    print()

    for i in range(1, n 1):
        print(i, " |{:3d}".format(i), end='')
        for x in range(1, n 1):
            print("{:3d}".format(i*x), end="")

        print()

main()

Desired Output

CodePudding user response:

def main():

    print("This is a times-table.")

    n = int(input("Enter a number: "))
        
    for i in range(1,n 1):
        print(" {:3d}".format(i), end='')
    print()

    for i in range(1, n 1):
        print(i, " |{:3d}".format(i), end='')
        for x in range(2, n 1):
            print("{:3d}".format(i*x), end="")

        print()

main()

It was in the x for loop, where you needed to start from 2. This is because, in the for loop above it, you already set the first number by stating |{:3d}. You could either remove that, or start from 2.

Furthermore, you probably want to improve on this by setting the numbers above the columns on the right spot. I'll give you a headstart by giving you a working solution for the tables up to 9.

def main():

    print("This is a times-table.")

    n = int(input("Enter a number: "))
    
    print("   |",end="")
    for i in range(1,n 1):
        print("{:3d}".format(i), end='')
    print()
    print("--- -" "---"*n)

    for i in range(1, n 1):
        print(i, " |{:3d}".format(i), end='')
        for x in range(2, n 1):
            print("{:3d}".format(i*x), end="")

        print()

main()

Now for you is the question, how to continue when multiplications exceed 2 digits.

CodePudding user response:

for row in range(0, 10): for col in range(0, 10): num = row * col if num < 10: empty = " " else: if num < 100: empty = " " if col == 0: if row == 0: print(" ", end='') else: print(" ", row, end='') elif row == 0: print(" ", col, end='') else: print(empty, num, end='') print()

  • Related