0

The output of this program is a table, but it is kind of messy. How to align the different columns? Thanks

Code:

import math   

for a in range(1, 10):
    x = 3.0
    while True:
        y = (x + a/x) / 2
        if y == x:
            break
        x = y  
    sq = math.sqrt(a)
print float(a), sq, x, abs(sq - x)
Quester
  • 1,969
  • 4
  • 15
  • 13

1 Answers1

2

Use str.format:

import math   

for a in range(1, 10):
    x = 3.0
    while True:
        y = (x + a/x) / 2
        if y == x:
            break
        x = y  
    sq = math.sqrt(a)
    print '{:>5} {:>5.10f} {:>5.10f} {:>5.10f}'.format(float(a), sq, x, abs(sq - x))

prints

  1.0 1.0000000000 1.0000000000 0.0000000000
  2.0 1.4142135624 1.4142135624 0.0000000000
  3.0 1.7320508076 1.7320508076 0.0000000000
  4.0 2.0000000000 2.0000000000 0.0000000000
  5.0 2.2360679775 2.2360679775 0.0000000000
  6.0 2.4494897428 2.4494897428 0.0000000000
  7.0 2.6457513111 2.6457513111 0.0000000000
  8.0 2.8284271247 2.8284271247 0.0000000000
  9.0 3.0000000000 3.0000000000 0.0000000000
falsetru
  • 357,413
  • 63
  • 732
  • 636