Search code examples
pythonmathtabular

Printing table in python without modules


We have this assignment and I spend some time on it...
Test script wants us to print this:

>>> input([0, 1, 2, 3])
     x | sin(x) | cos(x) | tan(x)
---------------------------------
  0.00 |   0.00 |   1.00 |   0.00
  1.00 |   0.84 |   0.54 |   1.56
  2.00 |   0.91 |  -0.42 |  -2.19
  3.00 |   0.14 |  -0.99 |  -0.14

without using modules(we can use module MATH just using this as a hint https://docs.python.org/3/library/string.html#format-specification-mini-language

Please help. This is what I have now:

import math
def input(list):
    rad=[]
    sinvr=[]
    cosvr=[]
    tanvr=[]
    for el in list:
        sin=math.sin(el)
        sinvr.append(sin)
        cos=math.cos(el)
        cosvr.append(cos)
        tan=math.tan(el)
        tanvr.append(tan)
    print ("     x | sin(x) | cos(x) | tan(x)\n---------------------------------")

Solution

  • In python3 you can use the format method from string:

    print("{:^10.2f}|{:^10.2f}|{:^10.2f}|{:^10.2f}|".format(x,sin(x),cos(x),tan(x)))
    

    Notice that ^ means to center, 10 is the total size of the 'cell' and .2f is to print a float with 2 decimal places, change it according to your needs.