Table of Squares and Cubes

Question:

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
Asked By: Renee

||

Answers:

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('numbertsquaretcube')

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.

Answered By: bherbruck

Here we can specify the width of the digits using format in paranthesis

print('number    square    cube')
for x in range(0, 6):
  print('{0:6d}t {1:7d}t {2:3d}'.format(x, x*x, x*x*x))

This would result in

number    square    cube
     0         0       0
     1         1       1
     2         4       8
     3         9      27
     4        16      64
     5        25     125
Answered By: sharath k

There is a somewhat more terse method you might consider that also uses format, as you guessed. I think this is worth learning because the Format Specification Mini-Language can be useful. Combined with f-stings, you go from eight lines of code to 3.

print('numbertsquaretcube')
for number in range(0, 6):
    print(f'{number:>6}{number**2:>8}{number**3:>6}')

The numbers here (e.g.:>6) aren’t special but are just there to get you the output you desired. The > however is, forcing the number to be right-aligned within the space available.

enter image description here

Answered By: hrokr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.