Printing a table in Python

17,504

This is using alignement options from the format method.

product = 0
for x in range(1,11):
    for y in range(1,11):
        product = x * y
        print('{:<4}'.format(product), end='')
    print()

Reference: Format specification mini-language

Share:
17,504

Related videos on Youtube

Katie Stearns
Author by

Katie Stearns

Updated on June 04, 2022

Comments

  • Katie Stearns
    Katie Stearns almost 2 years

    I have an assignment to create a 10 by 10 table in Python and I'm using the end "\t" within my print function to prevent it from creating a new line. But, I need it to start a new line after of course 10 characters. How can I make it do that? Here's my code:

    product = 0
    for x in range(1,11):
        for y in range(1,11):
            product = x * y
            print(product, end="\t")
    

    I need it to look something like this:

    1   2   3   4   5   6   ...
    2   4   6   8   10  12  ...
    3   6   9   12  15  18  ...
    
    • zondo
      zondo about 7 years
      print() right after the inner loop.
    • mwarzynski
      mwarzynski about 7 years
      @zondo what if she uses 2.x version of Python? I would rather suggest print("").
    • zondo
      zondo about 7 years
      @mwarzynski: Python 2.x does not have the end keyword because print isn't a function.
    • mwarzynski
      mwarzynski about 7 years
      @zondo Okay, thanks. Good to know.
    • feqwix
      feqwix about 7 years
      You can use the print function in python 2.6+ using from __future__ import print_function as the first line of code in your script.
  • zondo
    zondo about 7 years
    print() automatically adds a new line to whatever is being printed. When you print a new line, you're actually adding two. Just use print() with no arguments.
  • flakes
    flakes about 7 years
    You probably want to more the print() line to after the inner loop. Otherwise you print a blank line at the start, and then leave the console cursor at the end of the last line!
  • Katie Stearns
    Katie Stearns about 7 years
    I think this is a bit past where I'm at in my class right now but I'll play with it anyways to see what it does :) Thanks!
  • Katie Stearns
    Katie Stearns about 7 years
    Hmm putting it inside the inner loop didn't seem to work. That seems to cancel the end argument and everything is starting a new line again even with the other print statement after it.
  • Katie Stearns
    Katie Stearns about 7 years
    Got it! if I put it like so: product = 0 for x in range(1,11): for y in range(1,11): product = x * y print(product, end="\t") print() It works now. Thanks for your help!