Search code examples
pythonmath

Table of Squares and Cubes


I am learning Python on my own and I am stuck on a problem from a book I purchased. I can only seem to get the numbers correctly, but I cannot get the title. I was wondering if this has anything to do with the format method to make it look better? This is what I have so far:

number = 0
square = 0
cube = 0

for number in range(0, 6):
    square = number * number
    cube = number * number * number
    print(number, square, cube)

What I am returning:

0  0  0
1  1  1
2  4  8
3  9  27
4  16 64
5  25 125

I would like my desired output to be this:

number    square    cube
     0         0       0
     1         1       1
     2         4       8
     3         9      27
     4        16      64
     5        25     125

Solution

  • You need to print the header row. I used tabs \t to space the numbers our properly and f-stings because they are awesome (look them up).

    number = 0
    square = 0
    cube = 0
    
    # print the header
    print('number\tsquare\tcube')
    
    for number in range(0, 6):
        square = number * number
        cube = number * number * number
        # print the rows using f-strings
        print(f'{number}\t{square}\t{cube}')
    

    Output:

    number  square  cube
    0       0       0
    1       1       1
    2       4       8
    3       9       27
    4       16      64
    5       25      125
    

    The only thing this doesn't do is right-align the columns, you'd have to write some custom printing function for that which determines the proper width in spaces of the columns based on each item in that column. To be honest, the output here doesn't make ANY difference and I'd focus on the utility of your code rather than what it looks like when printing to a terminal.