user3804711
user3804711

Reputation: 151

Python HTML Table

I am unable to create a HTML Table with this just what exactly am I doing wrong or what should I add to make this work. please help I just don't understand anymore.

Also this code is to generate a Fibonacci sequence from 0-50 and also display them in columns in a table.

A decimal column, hex column, oct column and a float with point precision of 2.

#!/usr/local/bin/python3

print('Content-type: text/html\n')

def fib(n):

    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a

<table>
    <tr>
    <th>Index Number</th>
    <th>Decimal</th>
    <th>Hexadecimal</th>
    <th>Octadecimal</th>
    <th>float</th>
</tr>

for i in range (0, 51):
    <tr>
        <td>i</td>
        <td>fib(i)</td>
        <td>hex(fib(i))</td>
        <td>oct(fib(i))</td>
        <td>'%.2f' % float(fib(i))</td>
    </tr>
</table>

Upvotes: 2

Views: 505

Answers (1)

Wolph
Wolph

Reputation: 80031

It's fairly easy with the help of string formatting (https://docs.python.org/2/library/string.html#formatstrings):

#!/usr/local/bin/python3

print('Content-type: text/html\n')

def fib(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a

print('''
    <table>
        <tr>
        <th>Index Number</th>
        <th>Decimal</th>
        <th>Hexadecimal</th>
        <th>Octadecimal</th>
        <th>float</th>
    </tr>
''')

for i in range (0, 51):
    print('''
    <tr>
        <td>{0}</td>
        <td>{1}</td>
        <td>{1:x}</td>
        <td>{1:o}</td>
        <td>{1:.2f}</td>
    </tr>'''.format(i, fib(i)))

print('</table>')

Upvotes: 2

Related Questions