Advertisement
wkm

Multiplication table

wkm
Jul 15th, 2014
5,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # Multiplication table. http://redd.it/2agwnq
  3. # wukaem, 2014
  4.  
  5.  
  6. def show_mtable(cols, rows=None):
  7.     """
  8.    Function printing multiplication table.
  9.    rows, cols - ints, dimensions of table. If rows not provided: rows = cols.
  10.    """
  11.     if not rows:
  12.         rows = cols
  13.  
  14.     # Calculate column width (minimum 2 chars spacing)
  15.     width = len(str(rows * cols)) + 2
  16.  
  17.     # First row: header
  18.     print(' ' * width + '|', end='')
  19.     for num in range(1, cols+1):
  20.         print('{0:>{1}}'.format(num, width), end='')
  21.     print('\n' + '-' * ((cols + 1) * width + 1))
  22.  
  23.     # Rest of rows
  24.     for row in range(1, rows+1):
  25.         print('{0:>{1}} |'.format(row, width-1), end='')
  26.         for col in range(1, cols+1):
  27.             print('{0:>{1}}'.format(row*col, width), end='')
  28.         print()
  29.  
  30.  
  31. def main():
  32.     show_mtable(10)
  33.  
  34.  
  35. if __name__ == "__main__": main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement