Search code examples
pythonpython-3.xlistpython-2.7programmers-notepad

How to create a table with data with a formula? (Python)


I'm learning Python by myself and I was doing an experiment, where I want to create two columns of data (column A and column B). However, my experiment needs calculated data. My goal is to create a data frame myself (as you do in excel), but I want to incorporate the formulas I need to get the calculated values for my data.

Would it be easier to use the print() and the escape characters required (\n for line break, \t for tab), to display a table on the screen such as the following?:

Hours (n) Total number
0 200
5 6400
10 204800
15 6553600

For example: the formula I'm using to create this table is Total number=200x2^n


Solution

  • You "could" use \n and \t but that will become awkward very quickly. A better approach is to use
    the f-string formatting options to align things as needed.
    In this example, your calculation (200 * 2^n) is part of the list comprehension that creates the table values for printing, all in one go. The 15 + 1 in the range function is needed to include your stated value of 15.

    table_values = [(n, 200 * 2**n) for n in range(0, 15+1, 5)]
    
    print(f"{'Hours (n)':<15} Total number")
    print("-" * 28)
    for h, t in table_values:
        print(f"{h :<15} {t:}")
    
    
    # Alternatively, right-aligned and with 000-separators...
    print(f"{'Hours (n)':<15} Total number")
    print("-" * 28)
    for h, t in table_values:
        print(f"{h :>2} {t:>24,}")
    

    The output would then look something like this:

    Hours (n)       Total number
    ----------------------------
    0               200
    5               6400
    10              204800
    15              6553600
    

    Alternative output including the number alignment and formatting:

    Hours (n)       Total number
    ----------------------------
     0                      200
     5                    6,400
    10                  204,800
    15                6,553,600