How do I get each row on a separate line?
Question:
This program prints a table with 5 rows and 3 columns. Each row needs to be on a separate line. Use end=""
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS) :
row = [0] * COLUMNS
table.append(row)
print(table)
Answers:
By itself, print()
can’t put spaces between a list’s elements it just calls an internal function of the list
class to ask what it should print. Instead, you can define your own special print function like this:
def printTable(table):
print('[')
for el in table:
print(f' {el},')
print(']')
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS):
row = [0] * COLUMNS
table.append(row)
printTable(table)
You could also pass each element of the array as a separate parameter with a generator expression and use the sep
keyword argument:
def printTable(table):
print('[')
print(*(f' {el}' for el in table), sep="n")
print(']')
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS):
row = [0] * COLUMNS
table.append(row)
printTable(table)
I also used an f-string to provide a bit of nice indentation, but this is optional.
You can use tabulate module.
#IMPORT TABULATE
from tabulate import tabulate
#YOUR CODE
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS) :
row = [0] * COLUMNS
table.append(row)
#PRINT
print(tabulate(table))
This program prints a table with 5 rows and 3 columns. Each row needs to be on a separate line. Use end=""
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS) :
row = [0] * COLUMNS
table.append(row)
print(table)
By itself, print()
can’t put spaces between a list’s elements it just calls an internal function of the list
class to ask what it should print. Instead, you can define your own special print function like this:
def printTable(table):
print('[')
for el in table:
print(f' {el},')
print(']')
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS):
row = [0] * COLUMNS
table.append(row)
printTable(table)
You could also pass each element of the array as a separate parameter with a generator expression and use the sep
keyword argument:
def printTable(table):
print('[')
print(*(f' {el}' for el in table), sep="n")
print(']')
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS):
row = [0] * COLUMNS
table.append(row)
printTable(table)
I also used an f-string to provide a bit of nice indentation, but this is optional.
You can use tabulate module.
#IMPORT TABULATE
from tabulate import tabulate
#YOUR CODE
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS) :
row = [0] * COLUMNS
table.append(row)
#PRINT
print(tabulate(table))