1

I am trying to write a function that passes this doctest:

Prints a table of values for i to the power of 1,2,5 and 10 from 1 to 10
left aligned in columns of width 4, 5, 8 and 13
>>> print_function_table()
i   i*2 i*5    i*10
1   1    1       1
2   4    32      1024
3   9    243     59049
4   16   1024    1048576
5   25   3125    9765625
6   36   7776    60466176
7   49   16807   282475249
8   64   32768   1073741824
9   81   59049   3486784401
10  100  100000  10000000000

I feel like I am almost there but I can't seem to left-align my columns.

the code i have is:

def print_function_table():
    i = 1
    s = "{:^4} {:^5} {:^8} {:^13}"
    print s.format("i", "i*2", "i*5", "i*10")
    while i <= 10:
        print s.format(i, i*2, i*5, i*10)
        i += 1
2
  • 1
    Side note: Use for i in range(1, 11): instead of a while loop. Commented May 18, 2011 at 5:08
  • 1
    Side note 2: Why require left-alignment, when right-alignment is easier and more readable? Commented May 18, 2011 at 5:09

1 Answer 1

5

What about...

def print_function_table():
    s = "{:<4} {:<5} {:<8} {:<13}"
    print s.format("i", "i*2", "i*5", "i*10")
    for i in range(1,11):
        print s.format(i, i**2, i**5, i**10)

?

Sign up to request clarification or add additional context in comments.

4 Comments

Note: "{} {}".format() is valid starting with Python 3.1+; for previous versions one should use "{0} {1}".format() (with explicit indexes), see docs.python.org/py3k/library/string.html §6.1.3.2.
@Joël Not really true, current python 2.7.3 doc mentions this too. Py3k features like to be backported
this would be prettier with eval instead of repeating the header :)
@ArnabDatta Maybe it'd look pretty, but for sure less clear as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.