[Tutor] multiplication table

Kent Johnson kent37 at tds.net
Sat Jan 10 14:07:23 CET 2009


On Sat, Jan 10, 2009 at 6:01 AM, prasad rao <prasadaraon50 at gmail.com> wrote:
> Hi
> I tried to print multiplication table using (*args) to pass parameters.and
> tried
> to print tables side by side.But the code looks messy .Is there a better way
> to do it.
> def mtab(*arg):
> for x in range(1,11):
>  print '%3d'%(x),'x','%3d'%(arg[0]),'=','%3d'%(x*arg[0]),(' '*5),\
> '%3d'%(x),'x','%3d'%(arg[1]),'=','%3d'%(x*arg[1]),(' '*5),\
> '%3d'%(x),'x','%3d'%(arg[2]),'=','%3d'%(x*arg[2]),(' '*5)
> print(('-')*10).center(78)
> for x in range (1,11):
>  print '%3d'%(x),'x','%3d'%(arg[3]),'=','%3d'%(x*arg[3]),(' '*5),\
> '%3d'%(x),'x','%3d'%(arg[4]),'=','%3d'%(x*arg[4]),(' '*5),\
> '%3d'%(x),'x','%3d'%(arg[5]),'=','%3d'%(x*arg[5]),(' '*5)

You have a lot of duplicated code. You can reduce the duplication by
using functions and loops.

The first step is to put all the print code into a function rather
than repeating the same three formatting expressions over and over:

def show(x, y):
    print '%3d'%(x),'x','%3d'%(y),'=','%3d'%(x*y),(' '*5),

Then mtab() can be written like this:

def mtab(*arg):
    for x in range(1,11):
        show(x, arg[0])
        show(x, arg[1])
        show(x, arg[2])
        print
    print(('-')*10).center(78)
    for x in range (1,11):
        show(x, arg[3])
        show(x, arg[4])
        show(x, arg[5])
        print

Now you can see that the show() statements are still repetitive, they
can be put into a loop:

def mtab(*arg):
    for x in range(1,11):
        for i in range(0, 3):
            show(x, arg[i])
        print
    print(('-')*10).center(78)
    for x in range (1,11):
        for i in range(3, 6):
            show(x, arg[i])
        print

This is OK except the interface is awkward; do you really want to tell
it each number for the table, or would you rather give it a range of
numbers? Also you can use another loop to eliminate the duplicated
printing of the tables:

def mtab(lower, upper):
    for start in range(lower, upper+1, 3):
        for x in range(1,11):
            for y in range(start, start+3):
                show(x, y)
            print
        print(('-')*10).center(78)

mtab(1, 11)

This does not give quite the same result as your original - it prints
the divider after each table - and it always prints three tables per
group, even if you didn't ask for it - but it is much simpler and more
flexible than your original.

Kent


More information about the Tutor mailing list