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
Related videos on Youtube
Author by
Katie Stearns
Updated on June 04, 2022Comments
-
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 about 7 years
print()
right after the inner loop. -
mwarzynski about 7 years@zondo what if she uses 2.x version of Python? I would rather suggest
print("")
. -
zondo about 7 years@mwarzynski: Python 2.x does not have the
end
keyword becauseprint
isn't a function. -
mwarzynski about 7 years@zondo Okay, thanks. Good to know.
-
feqwix about 7 yearsYou can use the
print
function in python 2.6+ usingfrom __future__ import print_function
as the first line of code in your script.
-
-
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 useprint()
with no arguments. -
flakes about 7 yearsYou 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 about 7 yearsI 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 about 7 yearsHmm 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 about 7 yearsGot 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!