Krenair

multiplication table cleaned up and commented

Oct 8th, 2013
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. maxNum = int(input("What number do you want to go up to? ")) + 1
  2.  
  3. firstColumnJustifyWidth = len(str(maxNum))
  4. justifyWidth = firstColumnJustifyWidth**2 # Rough guess at how much we'll need to space things out
  5. if justifyWidth == 1: # For 0 < x < 9
  6.     justifyWidth += 1
  7.  
  8. headerNumbers = ['X'.rjust(firstColumnJustifyWidth)] # Start off with just the 'X'
  9. for columnNumber in range(1, maxNum): # For each column
  10.     headerNumbers.append(str(columnNumber).rjust(justifyWidth)) # Add all the header numbers into the list...
  11. print(' '.join(headerNumbers)) # Join the list together with at least one space
  12.  
  13. for rowNumber in range(1, maxNum): # For each row...
  14.     formattedRowNumber = str(rowNumber).rjust(firstColumnJustifyWidth) # Format the row number for printing
  15.     rowData = []
  16.     for columnNumber in range(1, maxNum):
  17.         rowData.append(str(rowNumber * columnNumber).rjust(justifyWidth)) # For each column: Do the multiplication and format the result for printing
  18.     formattedRowData = ' '.join(rowData) # Join the list together with at least one space
  19.     print(formattedRowNumber + ' ' + formattedRowData)
Advertisement
Add Comment
Please, Sign In to add comment