Search code examples
pythonpython-2.xprettytable

Using PrettyTable, Can I write a function that will take inputs and add them into a table so I don't have to continuously repeat myself?


I made a multiplication table, but I had to manually type out the code to add to my table. I want to write a loop that does it for me so the multiplication table can go on as long as I tell it too. Right now its limited to how many times i'm willing to write the code.

lista = []
def mult(z):
    d = 0
    while d < 10:
        c = z * d
        lista.append(c)
        d += 1

x = input("What number?")
mult(x)


table = PrettyTable(["Number", "*", "Equals"])
table.add_row([x, 0, lista[0]])
table.add_row([x, 1, lista[1]])
table.add_row([x, 2, lista[2]])
table.add_row([x, 3, lista[3]])
table.add_row([x, 4, lista[4]])
table.add_row([x, 5, lista[5]])
table.add_row([x, 6, lista[6]])
table.add_row([x, 7, lista[7]])
table.add_row([x, 8, lista[8]])
table.add_row([x, 9, lista[9]])

print table

Solution

  • from prettytable import PrettyTable
    
    def mult_table(num, lastmult):
        lista = []
        table = PrettyTable(['Number', '*', 'Equals'])
    
        for i in range(lastmult + 1):
            c = num * i
            lista.append(c)
            table.add_row([num, i, c])
    
        print(table)
    
    num = int(input('What Number?:'))
    lastmult = int(input('Multiply by one to what number?:'))
    
    mult_table(num, lastmult)
    

    (This code uses python3)

    This way, it generates multiple table of any length as you want. this code uses for loop instead of while.

    If you want to start with another number, just pass that number to the first parameter of the range() function.